大家好,我编写了向数组列表添加名称的程序,但是如果您第2次写相同的单词,则循环停止并写,您给了该单词两次。但我不知道问题出在哪里,你能帮我个忙吗?
package recurring.word;
import java.util.ArrayList;
import java.util.Scanner;
public class RecurringWord {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
while(true){
System.out.print("Type a word: ");
String name = reader.nextLine();
words.add(name);
if (words.contains(name)) {
break;
}
System.out.println("You gave the word " + name + "twice");
}
}
}
答案 0 :(得分:2)
您在这里遇到逻辑错误:
words.add(name);
if (words.contains(name)) {
break;
}
您将word
添加到ArrayList
,然后立即添加,如果它在ArrayList
中,则您break
退出循环。您需要将其切换到:
if (words.contains(name)) {
break;
}
words.add(name);
这将检查您是否已经在将单词 键入之前将其添加到列表中。
您还可以在while
循环中使用print语句,这不是您想要的。将其移到外部:
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
String name;
while(true){
System.out.print("Type a word: ");
name = reader.nextLine();
if (words.contains(name)) {
break;
}
words.add(name);
}
System.out.println("You gave the word " + name + " twice");