Closed. This question needs debugging details。它当前不接受答案。












想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。

4年前关闭。





我为我的计算机科学课分配了一个作业:创建一个读取.txt文件并打印出其中所有整数的平均值的类。

我非常困惑,并且不断收到“ null(在java.util.Scanner中)”错误,对于任何指导或帮助将不胜感激。

这是我的代码:

public static void main() {
    public static void main() {
        File file = new File("numbers.txt");
        Scanner in ;
        try { in = new Scanner(file);
            while (in.hasNextLine()) {
                int i = in.nextInt();
                int sum = i;
                int x = sum;
                System.out.print(sum / x);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

最佳答案

尝试将其放在您的main方法中:


new File(getClass().getResource("numbers.txt").toURI().toURL().toExternalForm().replace("file:", ""));


更新:
您的文件应与您所在班级所在的文件包位于同一包中

09-30 15:44
查看更多