【发布时间】:2016-10-16 20:03:01
【问题描述】:
我的程序旨在搜索多维数组以查找用户输入的状态。然后它供应州鸟和花卉。但是我不知道我需要在哪里放置语句以退出循环。它将继续在数组中搜索输入,并像我想要的那样一遍又一遍地问问题。但是我尝试了几种不同的方法,当我输入 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;
}
}
}
【问题讨论】:
-
你试图跳出哪个循环,while() 或 for()
-
当收到输入“none”时,我试图跳出 while 循环。 @pmcevoy12 给了我我想要的东西。但是,现在我遇到了一个问题,即当我进入 2 字状态时,它会将我带回到提示符,而没有任何状态输出。我猜我的循环没有考虑空格或其他东西,但我不确定挂断在哪里。
-
为了考虑空格,您可以使用方法 nextLine() 而不是 Scanner 类的方法 next()。
标签: java arrays for-loop while-loop