Search code examples
java

Java homework help


I have this assignment that I've tried. But when I enter 1 it should not give any output as 1 is > 0 and 1 is not even but I still get output as:

Enter a +ve number
1
You entered 1
I'd asked for a +ve number :)

.

 import java.util.Scanner;
 class Main {
    public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.println("Enter a +ve number");
      int number = input.nextInt();
      System.out.println("You entered "+number);
      if(number > 0)
         if(number %2 == 0)
             System.out.println("Number"+number+" is even and +ve");
         else
             System.out.println("I'd asked for a +ve number :)");
     }
 }

Solution

  • Your else actually belongs to the 2nd if not the 1st if as the indentation shows.

    if(cond1)
     if(cond2) 
    else   // this else belongs to 2nd if not 1st if.
    

    is same as:

    if(cond1) {
     if(cond2) {
     } else {
     }
    }
    

    This is because the Java grammar says that an else belongs to the closest unmatched if to which it can possibly belong.

    If you want to match the else with first if you need to use parenthesis as:

    if(cond1) {
     if(cond2) {
     } 
    } else { 
    }