我的程序旨在搜索用户输入的状态的多维数组。然后它提供国家的鸟和花。但是,我不知道应该将语句放在什么位置才能退出循环。它将继续在数组中搜索输入,并一遍又一遍地询问问题,就像我希望的那样。但我尝试了几种不同的方法,当我输入none时,无法让它退出循环。
Scanner userInput = new Scanner(System.in);
while (true) {
System.out.print("Enter a State or None to exit: ");
String stateName = userInput.next();
for (int i = 0; i < stateInformation.length; i++) {
if (stateInformation[i][0].equalsIgnoreCase(stateName)) {
System.out.println(stateInformation[i][0] + ":\n " +
"The State bird is the " + stateInformation[i][1] + "\n " +
"The State Flower is the " + stateInformation[i][2]);
break;
}
}
}
发布于 2016-10-16 20:14:25
下面是如何在您选择的特定语句上使用break
:
myLabel:
while (true)
{
while (true)
{
break myLabel; // This will break out of the outer loop that has been labeled.
}
}
发布于 2016-10-16 20:12:51
我假设你想退出while循环。您应该在for-loop之前检查用户输入是什么,如果没有,则使用break。第二个选项是检查while的参数中的输入是否为none。
发布于 2016-10-16 20:13:32
假设您想要跳出for循环,如果您使用一个函数,然后使用return,如下所示:
private Object searchData(...)
{
for (Type t : types2) {
if (some condition) {
// Do something and break...
return object;
}
}
}
https://stackoverflow.com/questions/40074848
复制相似问题