简体   繁体   中英

java, counting the numbers entered by the user

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM