Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java homework help

Tags:

java

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 :)");
     }
 }
like image 448
user459246 Avatar asked Sep 27 '10 08:09

user459246


2 Answers

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 { 
}
like image 196
codaddict Avatar answered Oct 04 '22 10:10

codaddict


Check that the code actually follows the logic it ought to - indentation won't help you with flow control, that's what curly brackets {} are for.

like image 34
Piskvor left the building Avatar answered Oct 04 '22 12:10

Piskvor left the building