单词没有正确替换

时间:2017-12-09 02:47:10

标签: java

我正在编写一个带有字典和txt文件的类,如果txt文件中的单词不在字典中,那么它会让用户有机会更改错误的单词。在进行校正之后,它将输出校正的txt文件。

这是一个示例txt文件:

twinkx twinkx lottle star how I
lottle lamb its a warld of laughter a
warld of tears

例如,它会问我是否想要纠正twinkx,当我将其切换为闪烁时,它仍会输出与上面相同的东西,它仍然会说twinkx。这让我相信我的替代方法有问题。评论中描述了它的算法,所以我可能错过了一些东西。

    private void replace(String misspelled, String replacement){
    //TODO: Algorithm:
    //If wrongWords contains the misspelled word:
    //   get ALL the lineNumbers on where the misspelled word appears
    //   for each line number where it appears:
    //        in fileLines[line] replace misspelled with replacement
    //        (Hint: use one of the available methods in the String class to do the replacement)
    if(wrongWords.containsKey(misspelled))
       wrongWords.get(misspelled);
       for(String line : fileLine){
          line.replace(misspelled, replacement);
       }  
    }

以下是首先调用replace的方法:

private Scanner scan; // a Scanner to read user's input
private HashSet<String> dictionary;
private HashMap<String, ArrayList<Integer>> wrongWords;
private ArrayList<String> fileLine;


private void correctionMode(){   
  //for each line in fileLines:
  //   for each word in the line:
  //      if the word is in wrongWords:
  //            display the word and ALL the line numbers it appears on
  //            ask user if they like to replace?(y/n)
  //            if user chooses y: 
  //              ask for a new word and call the replace method replaceAll occurrences
  //            for either y or n delete word from wrongWords     
  //Hint: for parsing lines look back at the processFile()
  for(String line: fileLine)
    for(String w: line.split("\\s"))
       if(wrongWords.containsKey(w)){
           System.out.println(w + " " + wrongWords.get(w));
           System.out.println("replace all? (y or n): ");
           String r = scan.nextLine();
           if(r.equals("y")){
              System.out.println("Enter replacement: ");
              String r2 = scan.nextLine();
              replace(w, r2);
              wrongWords.remove(w);
           }
           else if(r.equals("n")){
              wrongWords.remove(w);
           }              
       }                        
}

1 个答案:

答案 0 :(得分:0)

行只是一个循环变量。你需要这样的东西:

    for (int i = 0; i < fileLine.size(); i++) {
        fileLine.set(i, fileLine.get(i).replace(misspelled, replacement));
    }