简体   繁体   English

else if 语句在我放入 while 循环时不起作用

[英]else if statement doesn't work when i put it in while loop

I have a problem, when I use if statement in while loop, it works with if, but it doesn't in else if我有一个问题,当我在 while 循环中使用 if 语句时,它适用于 if,但它不适用于 else if

I need from program to print the largest number and the second largest number我需要从程序打印最大的数字和第二大的数字

here is the code这是代码

int num = S.nextInt();
int max = num;
int max2 = num;
while (num != -1) {
    if (num > max)
        max = num;

    else if (max2 <= num && max > num)
        max2 = num;

num = S.nextInt();
}
System.out.println("The max = " + max);
System.out.print("The max 2 = " + max2 );

it's not the problem why not go into else if.it's logic problem.这不是问题为什么不进入 else if.it 是逻辑问题。
I can show you example我可以给你看例子

int num = S.nextInt();
int max = num;
int max2 = 0;
while (num != -1) {
    if (num > max){
        max2 = max;
        max = num;
    }else if (num > max2){
        max2 = num;
    }

    num = S.nextInt();
}
System.out.println("The max = " + max);
System.out.print("The max 2 = " + max2 );

the solution is解决办法是

  • if max find bigger number.then give original max number to max2.and the new number to max如果最大找到更大的数字。然后将原始最大数字给 max2.and 新数字给最大
  • in case the first num is the biggest.so we set max2 to 0.and if there is no bigger number than max,we do compare on max2如果第一个 num 是最大的。所以我们将 max2 设置为 0。如果没有比 max 更大的数字,我们会在 max2 上进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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