【发布时间】:2016-07-23 11:15:38
【问题描述】:
我遇到了这个项目的问题。基本前提是用户输入一个短语,它应该找到任何重复的单词以及有多少。
我的问题是多次输入一个单词时,例如... 你好你好你好你好
输出结果是;
"There are 2 duplicates of the word "hello" in the phrase you entered."
"There are 1 duplicates of the word "hello" in the phrase you entered."
这似乎只发生在这样的情况下。如果我输入一个随机短语,其中包含多个单词,它会显示正确答案。我认为这个问题与删除重复的单词以及它在短语中迭代的次数有关,但我就是无法理解它。我已经在各处添加了打印行,并改变了它以各种方式迭代的时间,我在 Java Visualizer 中通过它,但仍然找不到确切的问题。非常感谢任何帮助!
这是我的在线 Java 课程的作业,但仅用于学习/练习,不适合我的专业。尽管只是提供帮助,但我不是在寻找答案。
public class DuplicateWords {
public static void main(String[] args) {
List<String> inputList = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
int duplicateCounter;
String duplicateStr = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence to determine duplicate words entered: ");
String inputValue = scan.nextLine();
inputValue = inputValue.toLowerCase();
inputList = Arrays.asList(inputValue.split("\\s+"));
finalList.addAll(inputList);
for(int i = 0; i < inputList.size(); i++) {
duplicateCounter = 0;
for(int j = i + 1; j < finalList.size(); j++) {
if(finalList.get(i).equalsIgnoreCase(finalList.get(j))
&& !finalList.get(i).equals("!") && !finalList.get(i).equals(".")
&& !finalList.get(i).equals(":") && !finalList.get(i).equals(";")
&& !finalList.get(i).equals(",") && !finalList.get(i).equals("\"")
&& !finalList.get(i).equals("?")) {
duplicateCounter++;
duplicateStr = finalList.get(i).toUpperCase();
}
if(finalList.get(i).equalsIgnoreCase(finalList.get(j))) {
finalList.remove(j);
}
}
if(duplicateCounter > 0) {
System.out.printf("There are %s duplicates of the word \"%s\" in the phrase you entered.", duplicateCounter, duplicateStr);
System.out.println();
}
}
}
}
根据一些建议,我编辑了我的代码,但我不确定我的方向是否正确
String previous = "";
for(Iterator<String> i = inputList.iterator(); i.hasNext();) {
String current = i.next();
duplicateCounter = 0;
for(int j = + 1; j < finalList.size(); j++) {
if(current.equalsIgnoreCase(finalList.get(j))
&& !current.equals("!") && !current.equals(".")
&& !current.equals(":") && !current.equals(";")
&& !current.equals(",") && !current.equals("\"")
&& !current.equals("?")) {
duplicateCounter++;
duplicateStr = current.toUpperCase();
}
if(current.equals(previous)) {
i.remove();
}
}
if(duplicateCounter > 0) {
System.out.printf("There are %s duplicates of the word \"%s\" in the phrase you entered.", duplicateCounter, duplicateStr);
System.out.println();
}
}
【问题讨论】:
-
您正在迭代一个 ArrayList,同时从中删除项目。这会导致意外行为。一个安全的使用方法是
Iterator.remove(),见stackoverflow.com/a/223929/4190526 -
如果你想在删除数组的同时迭代一个数组,我建议你从数组的末尾开始迭代到顶部。
标签: java list arraylist iterator