我正在尝试完成这个算法,该算法应该用替换字替换txt文件中的拼写错误的单词。正如您所看到的,该算法由上面的注释描述,我已经完成了前两个部分,但我被困在for each line number where it appears:
部分。我在试图找出如何设置循环时遇到问题。如果有人能帮助我朝着完成这种方法的方向发展,我将非常感激!
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);
}
您可能会发现有用的其他值得注意的代码包括:
private void correctionMode(){
for(String line: fileLine)
for(String w: line.split("//s"))
if(wrongWords.containsKey(w)){
System.out.println(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);
}
}
此方法要求用户进行更正,然后转到替换方法,即我遇到问题的方法,如果用户想要进行更改。
private Scanner scan; // a Scanner to read user's input
private HashSet<String> dictionary;
private HashMap<String, ArrayList<Integer>> wrongWords;
private ArrayList<String> fileLine;
\\constructor
public SpellChecker(){
scan = new Scanner(System.in);
dictionary = new HashSet<String>();
wrongWords = new HashMap<String, ArrayList<Integer>>(); //array is line numbers where misspelled word appears
fileLine = new ArrayList<String>(); //each line is as separate element in the arraylist
}
类变量和构造函数也可能有用。
答案 0 :(得分:0)
您不需要在每个行的两个方法中都使用for循环。
// for each line number where it appears:
和
for(String line: fileLine)
将其放入其中任何一个:
private void replace(String misspelled, String replacement){
int i = 0;
for(String line: fileLine) {
if(line.contains(misspelled)) {
line.replaceAll(misspelled, replacement);
System.out.println("replaced word" + misspelled + "in line number" + i );
i++;
}else i++;
}
}