Reputation: 45
it doesn't count the second number entered by the user. I tried other things but still can get to it.
Scanner in = new Scanner(System.in);
int count = 0;
int num = in.nextInt();
int num2 = in.nextInt();
if (num > 0){
count++;
}
else if (num2 > 0){
count++;
}
System.out.println(count);
input: 2 21435 expected ouput: 2
Upvotes: 1
Views: 195
Reputation: 3027
to check and count each number separately you need to define condition for each variable:
if (num > 0) {
count++;
}
if (num2 > 0) {
count++;
}
and you can abbreviate it much better like:
count += num > 0 ? 1 : 0;
count += num2 > 0 ? 1 : 0;
Upvotes: 0
Reputation: 16104
if (num > 0){
count++;
}
else if (num2 > 0){
count++;
}
is about equivalent to (perhaps, it will make it clearer for you)
if (num > 0){
count++;
}
else {
// this block is entered only if "num <= 0"!
if (num2 > 0){
count++;
}
}
So, if your first test passes, the second will never be executed. Thus, you only ever have one increment tops.
What you want is more like
if (num > 0){
count++;
}
if (num2 > 0){
count++;
}
Here, the second condition gets evaluated, regardless of what the first has been evaluated to.
Upvotes: 2