我正在写一个检查重复的代码,这是由用户键入的。当用户输入第二个副本时,程序将停止并警告用户该副本。我的逻辑是,我将把给定的单词放到ArrayList中,然后检查当前ArrayList中的下一个给定单词是否已经存在。
public class RecurringWord {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
words.add(word);
int i = 0;
if (words.contains(words.get(i+1))) {
System.out.println("You gave the word " + words.get(i+1) + " twice");
}
i++;
break;
}
}
}发布于 2015-06-25 16:42:13
您需要进行一些重新组织和逻辑检查。如果你想在用户尝试添加同一个词两次时停止,然后停止并且根本不将它添加到列表中,那么你就不需要保留任何索引了。
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
if (words.contains(word)) {
System.out.println("You gave the word " + word + " twice");
break;
}
words.add(word);
}发布于 2015-06-25 16:42:56
尝试下面列出的内容
ArrayList<String> words = new ArrayList<String>();
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
if (words.contains(word)) {
System.out.println("You gave the word " + words.get(i+1) + " twice");
}else{
words.add(word);
break;
}发布于 2015-06-25 16:43:01
首先。对于您的需求,不需要使用迭代器i。其他请参阅评论:
Scanner reader = new Scanner(System.in);
Set<String> words = new HashSet<>();
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
if (words.contains(word)) {
System.out.println("You gave the word " + words + " twice");
break; // end the programm if the word exists twice
}
words.add(word); // add the new word after the check.
}在您的示例中,用户只能输入一个单词,在此之后程序员结束。
words.get(i+1)将导致Exception,因为该元素永远不会存在。从元素0开始,而不是从1开始。
此外,我建议您使用一个集合,如果它是一个无效的大小写,同一个词有两次:
Set<String> words = new HashSet<>();Set永远不会包含两个相等的字符串。
https://stackoverflow.com/questions/31045165
复制相似问题