Home > Mobile >  I want to keyboard input 3 integers and print the maximum value is "X" using if-else state
I want to keyboard input 3 integers and print the maximum value is "X" using if-else state

Time:05-29

In the last if statement, why I cannot use only else statement instead of else if statement, if I entered only else statement, the compiler generates an error saying not a statement.

import java.util.Scanner;
class today {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.print("Input number 1:");
        int num1 = input.nextInt();
        System.out.print("Input number 2:");
        int num2 = input.nextInt();
        System.out.print("Input number 3:");
        int num3 = input.nextInt();

        if (num1 > num2 && num1 > num3) {
            System.out.println("Maximum number is:"   num1);
        } else if (num2 > num1 && num2 > num3) {
            System.out.println("Maximum number is:"   num2);
        } else if (num3 > num1 && num3 > num2) {
            System.out.println("Maximum number is:"   num3);
        }
    }
}

CodePudding user response:

Its giving you error because else statement should not have any condition to validate. Check here to know more about if else Read more

if (hi < 5) {
  System.out.println("ok");
  }
else {
System.out.println("no");
}

See in above code else statement don't have any condition

so in your case it should be like this.

if(num1>num2 && num1>num3){
System.out.println("Maximum number is:" num1);
}

else if(num2>num1 &&  num2>num3){
System.out.println("Maximum number is:" num2);
}

else{
System.out.println("Maximum number is:" num3);
}

CodePudding user response:

It works well in my environment without any errors. Don't have to write "else" at the end. Advise you to check your environment. enter image description here

  •  Tags:  
  • java
  • Related