我的代码是一个“猜谜游戏”,如果你输入一个东南亚国家,它会显示一个“youarecorrect”文本,但如果不是这样,我的问题是,else循环与我输入的国家数组的长度相乘,如何停止循环plz?
代码--
package guessinggame;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
String ans;
String[] countries = {"Philippines", "Brunei", "Burma", "Cambodia",
"Timor Leste", "Indonesia", "Laos", "Malaysia", "Singapore", "Thailand", "Vietnam"};
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a Southeast Asian country");
ans = sc.nextLine();
for (int x=0; x<countries.length; x++) {
if (ans.equals(countries[x])){
System.out.println("Your answer (" + ans + ") is correct.");
}
else System.out.println("Your answer (" + ans + ") is incorrect.");
}
}
}
5条答案
按热度按时间wljmcqd81#
目前,您的代码接受用户输入,然后在一个循环中将用户输入与其中一个国家进行比较
这意味着如果你的列表有20个条目,如果输入不正确,用户会被告知20次。对于正确的输入,用户会被告知19次他错了,一次他是正确的。
您需要做的是:
你可以设置一个变量
找到匹配项后,将其设置为
true
。稍后,您的输出可能如下所示如果要优化代码,请在找到匹配项后立即终止循环。
6uxekuva2#
您需要在循环中添加break和一个标志,以了解用户是否回答错误。检查代码中的注解。我希望下面的代码能帮助您!
6psbrbz93#
cngwdvgl4#
干得好
efzxgjgh5#