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 :)");
}
}
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 {
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With