A simple Java conditional question.

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

import java.util.Scanner;
public class test {

    public static void main(String[] arg) 
        Scanner scan = new Scanner(System.in);

        System.out.println ("Enter an integer: ");
        int num = scan.nextInt();

            System.out.println(num + ") is a multiple of 3.");
            System.out.println(num + ") is a multiple of 5.");
            System.out.println(num + ") is a multiple of 7.");
            System.out.println(num + ") is a multiple of 9.");

        else {
            System.out.println ("No multiples").");



The exception statement is also displayed when an input value satisfying the condition is entered.

How can we exclude this phrase and print it out?

java conditional-statement

2022-09-20 10:39

1 Answers


The intention of the body code seems to be to run else through all of the if statements above, and when none of them exist. However, the if statement does not work like that.

else is only associated with the previous if or the previous if~if statement.

if (...)
else if (...)
else if (...)

The code above looks like an ideal chain condition.

if (...) // first
if (...) // second
if (...) // third
else // third-else

By linking conditional statements in this way, of course, the syntax inside if will only be executed when the conditions are right. However, all if except for the last are separate conditions that are not related to else.

In other words, else is executed as long as if is false just above it, no matter how it was executed above it.

2022-09-20 10:39

If you have any answers or tips

© 2022 pinfo. All rights reserved.