我需要一点帮助,我有以下代码:
Scanner s = new Scanner(System.in);
String userinput= s.nextLine();
String[] books = new String[10];
books[0] = "book1”;
books[1] = "book2";
if (Arrays.asList(userinput).contains(books[0])) {
System.out.println("right, what is the next book?");
}
else {
System.out.println("false");
}
我的目标是迭代数组并询问用户下一个输入,因此如果他写“book1”,我想自动询问“下一本书是什么?”我会等待他的答案是“book2”,依此类推,按时间顺序依次是 book3、4、5...。如果他在我期待“book2”时写了“book5”,那么一切都会重新开始,直到他按时间顺序写对为止
最佳答案
尝试阅读 3 本书。
String[] books = new String[3];
books[0] = "book1";
books[1] = "book2";
books[2] = "book3";
boolean flag = true;
while(flag){ //outer loop
int counter = 0; //check for total right answers
for(int i=0;i<books.length;i++){ //iterate over all books
System.out.print("Choose book " + (i+1) +" name: ");
String userinput= s.nextLine();
if (Arrays.asList(userinput).contains(books[i])) {
counter++;
System.out.println("right, what is the next book?");
if(counter == books.length){ //in case all choices are correct
flag = false;
}
} else {
System.out.println("Wrong");
break;//terminate inner loop
}
}
}
关于java - 如果用户输入在 Java 中按时间顺序排列,如何迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59708702/