【发布时间】:2016-10-22 06:48:13
【问题描述】:
问题 1: 如果用户输入的 int 大于或等于 2,则第一个 if 语句变为 true 并执行代码设置 boolean error1 变量为假。根据我的while 语句,do 循环仅应在error1 变量为true 时重复。然而,无论如何循环都会重复。
如何使第一个if 语句设置为true 时退出循环?
问题 2:如果用户输入的不是 int,我将使用 try-catch 代码来帮助重复 do-while 循环。但是,当输入abc 或12.3 之类的内容时,会执行try 代码的第一个println,而要求用户输入的try 语句的第二行将被忽略,catch 代码是再次执行。这成为一个没有用户输入的非终止循环。
catch 代码执行后,如何获取请求用户输入的语句?
这是我的代码:
import java.util.InputMismatchException;
import java.util.Scanner;
public class DeepbotCalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
boolean error1 = false;
do {
try {
System.out.println("How many points do you currently have?");
points = input.nextInt();
if (points >= 2){
error1 = false;
}
else if (points > 0 && points < 2) {
System.out.println("you need at least 2 points");
error1 = true;
}
else if (points <= 0) {
System.out.println("Please enter a positive whole number");
error1 = true;
}
} catch (InputMismatchException e){
System.out.println("Please enter a positive whole number.");
error1 = true;
}
} while (error1 = true);
【问题讨论】:
-
你为什么用解决方案编辑你的问题?
-
照@SotiriosDelimanolis 所说的去做。未来的读者将如何理解答案/解决方案。
-
永远不要用您的解决方案来编辑您的问题以覆盖原始代码。如果您想添加解决方案,您可以在最后将其作为问题的更新。请记住始终格式化代码中的所有内容,而不是使用撇号。
-
我将解决方案添加到我的问题中,因此未来的读者不会多次回答问题的同一部分。以后我不会这样做了。在谈论我的代码时,我也会使用正确的格式。
标签: java loops if-statement try-catch do-while