gpt4 book ai didi

java - 如何用某个变量结束 while 循环

转载 作者:行者123 更新时间:2023-12-01 17:43:51 24 4
gpt4 key购买 nike

我正在制作一个带有 while 循环的奇数或偶数程序。我想弄清楚如何以某个数字结束 while 循环。现在我有 1 来继续循环,并尝试使 2 成为终止循环的数字。还试图找出如果用户输入除数字(如字母/单词)之外的任何内容如何终止程序。

package oddoreven;
import java.util.Scanner;

public class oddoreven {
public static void main (String[] args){
int num;
int x = 1;
while(x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}

}

}

最佳答案

您应该尝试使用“真正的终止条件”来终止 while 循环(或任何与此相关的循环);它更干净,应该更容易被其他人理解。

就您而言,我认为最好有一个 do-while 循环,并围绕此逻辑添加一些条件:num % 2 == 0 code> 和一个用于处理用户输入/验证的内部 while 循环。

如果你还想突然中断循环,看看 here .

If you still need some help with the code, hit me up and I'll sketch up something.

关于java - 如何用某个变量结束 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57791655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com