方法是非法的表达式开始

时间:2015-08-14 13:49:10

标签: java methods

下面是一些试图找到超过一定数量字符的第一个单词的代码。

public class FirstMatch {
    public static void main(String[] args) throws java.io.FileNotFoundException {
        Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
        String longWord = "";
        boolean found = false;

        public void threshold (int Threshold) {
            while (in.hasNext() && !found) {
                String word = in.next();
                if (word.length() > Threshold) {
                    longWord = word;
                    found = true;
                }
            }
            System.out.println("The first long word is: " + longWord);
        }
    }
}

(在上面的代码中我没有复制所有的import语句) 出于某种原因,我的阈值方法会返回非法的表达式开始。我认为这是一个愚蠢的错误,但无法弄清楚错误是什么......

1 个答案:

答案 0 :(得分:3)

您应该使用threshold方法声明main方法。

方法只能在类级别创建,而不能在其他方法中创建。

import java.io.FileReader;
import java.util.Scanner;

public class FirstMatch {

    public static void main(String[] args) throws java.io.FileNotFoundException {
        Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));    
        threshold(in, 10);
    }

    public static void threshold(Scanner in, int threshold) {
        String longWord = "";
        boolean found = false;
        while (in.hasNext() && !found) {
            String word = in.next();
            if (word.length() > threshold) {
                longWord = word;
                found = true;
            }
        }
        System.out.println("The first long word is: " + longWord);
    }

}