【发布时间】:2015-12-28 10:38:43
【问题描述】:
我最近开始学习 Java,在测试一些东西时遇到了一个问题。这可能是一个非常简单的问题,但我似乎无法解决它。 这是我的代码:
int firstj = 1;
if (firstj == 1) {
String choice = "Type a number between 1 and 4";
System.out.println(choice);
while (true) {
if (firstj == 1) {
Scanner third = new Scanner(System.in);
String thirdch = third.nextLine();
while (true) {
if (thirdch.equals("1")) {
System.out.println("Show choice and accept input again ");
System.out.println(choice);
break;
} else if (thirdch.equals("2")) {
System.out.println("Show choice and accept input again ");
System.out.println(choice);
break;
} else if (thirdch.equals("3")) {
System.out.println("Show choice and accept input again ");
System.out.println(choice);
break;
}
else if (thirdch.equals("4")) {
// I need this to break the loop and move on to the
// "Done." string
break;
}
else {
System.out.println("Type a number between 1 and 4");
thirdch = third.nextLine();
}
}
}
}
}
String done = "Done";
System.out.println(done);
我想这样当你输入 1、2 或 3 时,你会得到一个字符串,告诉你再次输入一个数字并接受用户输入,而当你输入 4 时,循环中断并转到字符串完成。如果你能用简单的代码帮助我解决这个问题,我将不胜感激,因为我不知道任何更高级的东西。
【问题讨论】:
-
你的意思是要跳出外循环吗?
-
您正在突破内部 while 循环,而不是外部 while 循环。所以 while(true) 总是正确的。
-
"break" 只能让您脱离 1 个循环。您最基本的问题是无限循环。有一个无限循环已经够糟糕了,你实际上有两个。是时候重构你的代码了。
标签: java loops if-statement while-loop break