Создание и проверка набора карт
Всем привет. Помогите с задачей. Сначала попросите пользователя ввести нужное количество карточек. Затем попросите ввести термин и определение каждой карточки. Спросите обо всех новых словах, которые он ввел. Программа должна дать термин и попросить дать определение. Вопрос. Как отработать второй for до начала запуска третьего for? При этом в третьем нужен j. Почему equals не сравнивает?
Пример вывода:
Input the number of cards:
> 2
The card #1:
> black
The definition of the card #1:
> white
The card #2:
> white
The definition of the card #2:
> black
Print the definition of "black":
> white
Correct answer.
Print the definition of "white":
> blue
Wrong answer. The correct one is "black".
import java.util.Scanner;
public class MakeItYourOwn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input the number of cards:");
int size = scanner.nextInt(); // Read the size of the array from the keyboard and write to "size"
String[] arr = new String[size]; // Create an int array of size "size"
for (int i = 0; i < arr.length; i++) {
System.out.println("The card #" + (i + 1) + ":");
arr[i] = scanner.next();// fill the array color card with the keyboard
for (int j = 0; j < arr.length; j++) {
System.out.println("The definition of the card #" + (i + 1) + ":");
arr[j] = scanner.next();// fill the array definition card with the keyboard
for (int k = 0; k < arr.length; k++) {
System.out.println("Print the definition of \"" + (arr[j]) + "\":");
arr[k] = scanner.next();// fill the array definition card with the keyboard
if (arr[j].equals(arr[k])) {
System.out.println("Correct answer.");
} else {
System.out.println("Wrong answer. The correct one is \"" + (arr[j]) + "\".");
}break;
}break;
}
}
}
}
Ответы (1 шт):
Автор решения: Poul
→ Ссылка
Сделал через Map. Как оптимизировать решение?
public static void main(String[] args) {
LinkedHashMap<String, String> color = new LinkedHashMap<String, String>();
Scanner scanner = new Scanner(System.in);
System.out.println("Input the number of cards:");
int size = Integer.parseInt (scanner.nextLine ()); // Read the size of the array from the keyboard and write to "size"
String[] arr = new String[size]; // Create an int array of size "size"
for (int i = 0; i < arr.length; i++) {
System.out.println("The card #" + (i + 1) + ":");
String a = scanner.nextLine();// fill the array color card with the keyboard
System.out.println("The definition of the card #" + (i + 1) + ":");
String b = scanner.nextLine();// fill the array definition card with the keyboard
color.put(a, b);
}
for (Map.Entry m : color.entrySet()) {
System.out.println("Print the definition of \"" + (m.getKey()) + "\":");
if (scanner.nextLine().equals(m.getValue())) {
System.out.println("Correct answer.");
} else {
System.out.println("Wrong answer. The correct one is \"" + (m.getValue()) + "\".");
}
}
}