【发布时间】:2019-04-18 23:12:25
【问题描述】:
基本上我想在用户输入字母“q”而不是整数时退出程序。
尝试了几个小时,尝试通过添加解决它
if(quit.equalsIgnoreCase("q")){
System.exit(0)
}
在 try 语句中。尝试从 try 语句中删除 Scanner 并将其添加到 while 循环之前,然后像这样创建一个新变量:
String quit = "";
while (quit != "q"){
//code
}
然后在代码中再次添加一种退出方式,但这不起作用。
while (true) {
try {
int randomNumberOne = ThreadLocalRandom.current().nextInt(10, 21); //generates a number between 10 and 20
int randomNumberTwo = ThreadLocalRandom.current().nextInt(10, 21); //generates a number between 10 and 20
System.out.println("Type and enter \"q\" to quit at any time \n \n");
System.out.println(randomNumberOne + " % " + randomNumberTwo + " = ?"); //prints the question
Scanner userInput = new Scanner(System.in);
int remainderInput = userInput.nextInt();
if (remainderInput == randomNumberOne % randomNumberTwo) { //if they get the question right
userScore += 20; //adds 20 points
performance += 1; //adds 1 to the correct question counter
performancetotal += 1; //adds 1 to the total question counter
System.out.println("Correct answer, Current Score: " + userScore + ", performance: " + performance + "/" + performancetotal + "\n");
continue;
}
else { //if they get the question wrong
userScore += 0; //adds no points
performance += 0; //adds nothing to correct question counter
performancetotal += 1;
System.out.println("Incorrect answer, Current Score: " + userScore + ", performance: " + performance + "/" + performancetotal + "\n");
continue;
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input\n");
}
}
}
这是我当前的代码,除了顶部的一些变量不应该影响代码。
程序应该永远运行,直到用户输入“q”,然后它将停止运行。那里有 try/catch 语句,因此它们只能输入整数(当然“q”除外)。
任何帮助将不胜感激。
【问题讨论】:
-
程序永远运行,直到用户输入“q”,然后它就会停止运行。 这不是重点吗?有什么问题?
-
@shmosel 抱歉。意思是“程序应该永远运行”。只是试图解释它的作用。问题是我找不到让它退出atm的方法。显然我已经尝试过诸如 System.exit(0) 之类的东西,但它不起作用。
-
您当前的 sn-p 没有
break;语句或while条件,那么您为什么希望它停止? -
你想设置一个标志(布尔值是好的),当输入 q 并检查你的 while 循环与那个标志。
标签: java while-loop try-catch exit