gpt4 book ai didi

java - Sentinel 问题与循环允许在 java 中输入 quit 来结束程序

转载 作者:行者123 更新时间:2023-12-01 12:30:41 26 4
gpt4 key购买 nike

我在底部遇到问题,我试图将哨兵退出键设置为退出。我不确定我到底应该怎么做。

整数;

    do
{

Scanner Input = new Scanner(System.in);
System.out.print("Enter a positive integer or q to quit program:");
number = Input.nextInt();
}
while(number >= 0);

do
{

Scanner Input = new Scanner(System.in);
System.out.print("Input should be positve:");
number = Input.nextInt();
}
while(number < 0);

do
{

Scanner quit = new Scanner(System.in);
System.out.print("Enter a positive integer or quit to end program");
input = quit.nextstring();


}
while (!input.equals(quit))//sentinel value allows user to end program
{
quit = reader.next()

最佳答案

一些提示:

  • 不要每次迭代都初始化一个新的扫描仪,那真的是昂贵的。
  • 请注意,正如您所写,如果用户输入否定数字,他们无法“回到”第一个 while 循环以保持输入正数。
  • 我猜你想一次性完成这一切循环,而不是三个,否则这些操作必须在突破所有 3 个哨兵条件的序列。
  • System.out.print() 不会添加新行,这看起来很尴尬。

根据这些假设,这里的版本有一个哨兵变量 endLoop,如果满足退出条件(即用户输入“退出”),该变量就会重置。如果他们输入负数,则会打印“输入应该为正”消息,然后循环将重新开始,如果他们输入正数,则不会发生任何事情(我标记了在哪里添加任何操作)并且循环将重新开始。我们仅在检查输入(字符串)不是“退出”后才将其转换为 int,因为如果我们尝试将字符串(如“退出”)转换为 int,程序将会崩溃。

Scanner input = new Scanner(System.in);
boolean endLoop = false;
String line;
while (!endLoop) {
System.out.print("Enter a positive integer or 'quit' to quit program: ");
line = input.nextLine();
if (line.equals("quit")) {
endloop = true;
} else if (Integer.parseInt(line) < 0) {
System.out.println("Input should be positive.");
} else {
int number = Integer.parseInt(line);
//do something with the number
}
}

编辑为使用“quit”而不是 0 作为终止条件。请注意,如果用户输入数字或“退出”以外的任何内容,该程序将崩溃。

关于java - Sentinel 问题与循环允许在 java 中输入 quit 来结束程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943644/

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