我应该使用什么循环?
我应该在 Java 中的两种语言之间做一个猜字游戏,我不确定在控制用户输入时应该使用什么类型的循环!我有三个“条件/条款”
- 如果用户输入正确答案
- 如果用户有拼写错误
- 如果用户
q输入退出游戏
我首先想到使用 for 循环,但我似乎没有弄清楚!
我的代码现在看起来像这样
public static int takeTest(ArrayList<Sweng> Wordlist) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < Wordlist.size(); i++) {
System.out.println(Wordlist.get(i).getSweWord());
String answer = keyboardInput.nextLine();
}
//...
}
回答
如果不知道循环需要执行多少次,可以使用do-while循环。
这个循环首先执行do括号内的代码,然后检查条件。
这是一个实现示例:
Scanner s = new Scanner(System.in);
String input; // a variable to store the input
do {
System.out.println(/*your question here*/);
input = s.nextLine();
// do something
} while(!input.equals("q")); // exit the loop if 'input' equals "q"
否则,你可以做类似的事情,但这是一种非常糟糕和粗暴的方式。我不建议你使用它。
注意:您需要使用您的ArrayList<Sweng> WordList. 这只是一个例子!
ArrayList<String> questions = new ArrayList<String>();
ArrayList<ArrayList<String>> possibleAnswers = new ArrayList<ArrayList<String>>(); // list of a list because we need a set of strings for every questions
ArrayList<String> correctAnswers = new ArrayList<String>();
// init the lists
Scanner s = new Scanner(System.in);
int result = 0;
boolean quit = false; // if true, then quit the for loop
for(int i = 0; i < questions.size(); i++) { // repeat 'questions.size()' times
String answer = null;
do {
if(answer != null) System.out.println("This isn't a valid answer!"); // if 'answer' is null, don't show this output because it's the first time in the loop
System.out.println(questions.get(i));
answer = s.nextLine();
if(answer.equals("q")) { // if input is "q", set 'quit' to 'true' and break the do-while loop
quit = true;
break;
}
} while(!possibleAnswers.get(i).contains(answer)); // if the answer is a valid answer, quit the loop
if(quit) break; // if quit is true, break the for loop
if(answer.equals(correctAnswers.get(i))) { // check for correct answer
System.out.println("Correct!");
result++;
} else System.out.println("Wrong!");
}
System.out.println("You scored " + result + "!");