读取文件,并使用Word类,方法处理单词

时间:2013-08-30 19:21:22

标签: java string class file-io word

我正在尝试创建一个Word类来处理文件导入的每个单词。

Word Class需要区分句子结尾/开头的标点符号,增加有效单词,并增加每个音节。

我的问题是让扫描程序将单词传递给Word类,以便处理它们的方法。错误发生在“word = scan.next();.”错误消息是“不兼容的类型:必需的Word,找到字符串。”

感谢您的帮助......

System.out.println("You chose to open the file: " +
            fc.getSelectedFile().getName());
            scan = new Scanner(fc.getSelectedFile());
            while (scan.hasNext()) 
            {
                Word word = new Word();
                word = scan.next();

Word Class

public class Word {
    private int wordCount, syllableCount, sentenceCount;
    private double index; 
    private char syllables [] = {'a', 'e', 'i', 'o', 'u', 'y'};;
    private char punctuation [] = {'!', '?','.'};;


    public Word()
    {
        wordCount = 0;
        syllableCount = 0;
        sentenceCount = 0;
    }

    public void Word(String word)
    {
        if(word.length() > 1)
        {
            for(int i=0; i < punctuation.length; i++)
            {
                if(punctuation[i] != word.charAt(word.length()-1))
                {
                    wordCount++;
                }
                else
                    sentenceCount++;
            }
            for(int i = 0; i < syllables.length; i++)
            {
                for(int j = 0; j < word.length(); j++)
                {
                    if(syllables[i] == word.charAt(j))
                    {
                        syllableCount++;
                    }
                }
            }
        }
        System.out.println(word);
    }
}

1 个答案:

答案 0 :(得分:2)

问题在于,scan.next()会返回String而不是Word对象,您无法像这样分配它。

试试这个:

while (scan.hasNext()) {
    Word word = new Word(scan.next());
    //...
}

要做到这一点,你需要一个像这样的构造函数:

public Word(String s){
    //...
}