[英]Sentinel issue with loop to allow to enter quit to end program in java
I'm having trouble at the bottom part where i am trying to set the sentinel exit key to quit.. im not sure exactly how i am supposed to do it. 我在底部尝试设置前哨出口键退出时遇到麻烦..我不确定我应该怎么做。
int number; 整数
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()
A couple tips: 几个提示:
Working on these assumptions, here's a version that has one sentinel variable endLoop
that gets reset if the quit condition is met, ie the user enters 'quit'. 根据这些假设,这里有一个带有哨兵变量
endLoop
的版本,如果满足退出条件,即用户输入“ quit”,该变量将重置。 If they enter a negative number, the "Input should be positive" message will print, then the loop will start over, and if they enter a positive number then nothing will happen (I marked where to add whatever action goes there) and the loop will start over. 如果他们输入一个负数,将显示“输入应该为正”消息,然后循环将重新开始,如果他们输入一个正数,则将不会发生任何事情(我标记了在此处添加任何操作的位置),然后循环将重新开始。 We only cast the input (which is a String) to an int after checking that it isn't 'quit', because if we try to cast a String (like 'quit') to an int, the program will crash.
我们仅在检查输入是否为“退出”之后才将输入(它是一个字符串)转换为一个int,因为如果我们尝试将一个字符串(如“ quit”)转换为一个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
}
}
Edited to use 'quit' instead of 0 for termination condition. 编辑为终止条件使用'quit'而不是0。 Note that this program will crash if the user enters anything other than a number or 'quit'.
请注意,如果用户输入数字或“退出”以外的任何内容,该程序将崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.