我正在为课堂作业设置一个拼写检查程序。
我正在尝试用另一个文件检查一个文件中的单词。
我目前遇到错误:
spelling.java:29: error: cannot find symbol
if(checkMe.next().equals(dicArr[i])){
^
symbol: variable dicArr
location: class spelling
1 error
你能告诉我我做错了什么或者用我的方法可以改进什么吗?非常感谢。
import java.util.*;
import java.io.*;
public class spelling{
public static void main(String args[]) throws FileNotFoundException {
//read the dictionary file
Scanner dicIN = new Scanner(new File("dictionary.txt"));
Scanner spellCheckFile = new Scanner(new File("checkMe.txt"));
String inputWord;
int i = 0;
//create arraylist to pass dictionary through, then I can define the size of my array
ArrayList<String> dicList = new ArrayList<String>();
while(dicIN.hasNext()){
dicList.add(dicIN.next());
String[] dicArr = dicList.toArray(new String[dicList.size()]);
}
//Scan through checkMe file to see if the words occur in the dictionary
Scanner checkMe = (spellCheckFile);
while(checkMe.hasNext())
{
if(checkMe.next().equals(dicArr[i])){
i++;
} else{
System.out.println("The word " + checkMe + "doesn't exist in the dictionary");
}
}
//System.out.println(dicList);
}
}
答案 0 :(得分:0)
您在while循环体中声明dicArr
。它在while循环体外不可见。
我不确定你要做什么,但我认为你需要在声明dicArr
之前关闭while循环:
while(dicIN.hasNext()){
dicList.add(dicIN.next());
} // <-- Add closing brace here.
String[] dicArr = dicList.toArray(new String[dicList.size()]);
// } // <-- Remove closing brace here.
答案 1 :(得分:0)
尝试在所有循环之前声明此String[] dicArr = null;
:
String[] dicArr = null;
ArrayList<String> dicList = new ArrayList<String>();
while(dicIN.hasNext()){
dicList.add(dicIN.next());
dicArr = dicList.toArray(new String[dicList.size()]);
}
//Scan through checkMe file to see if the words occur in the dictionary
Scanner checkMe = (spellCheckFile);
while(checkMe.hasNext())
{
if(checkMe.next().equals(dicArr[i])){
.....}
答案 2 :(得分:0)
你的i ++令人困惑 - 你应该有2个循环:
首选:
1使用Set for your dictionnary
2检查每个单词,你只需要做set_string.contains(new_word)
例如
设置set_string = new HashSet();
set_string.add(new_string);
if(set_string.contains(another_string))...
Set保留唯一元素。搜索很简单。