【发布时间】:2018-03-17 22:40:33
【问题描述】:
这是我的代码。它向用户询问术语和定义,然后对用户进行测验。 (它告诉用户术语,然后用户键入答案。)程序使用数组来存储术语和定义。如果用户没有得到正确的定义,程序会询问用户是否想再次研究它。如果是这样,他们将输入 yes,程序会将其存储在单独的数组中。在程序对用户进行所有术语和定义的测验后,第 2 轮开始,程序将仅对用户进行加星定义的测验。问题是,代码只运行一次 for 循环(在第 1 轮对用户进行测验),然后跳到第 2 轮。为什么会这样?我已经尝试查看其他人的问题和答案,但我似乎无法在我的代码中找到问题。
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i <= number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}
}
【问题讨论】:
-
无关:请阅读有关 java 命名约定的信息。您不要在普通变量名中使用 _!
-
也许也可以将
for (int i = 0; i <= number_terms; i++)更改为for (int i = 0; i < number_terms; i++),<=更改为<? -
也许你想发一个minimal reproducible example。这一切不可能是最小的。
标签: java arrays loops for-loop