我目前正在尝试创建一个Java程序,该程序允许扫描程序从.txt文件读取100个整数,然后让该程序输出100个数字的平均值。在读取代码时,它还必须检查是否有错误。 E.G(.txt文件中有一个字母,而不是整数)。

这是我到目前为止的代码:

package NumFile;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;

public class NumFile {
    public static void main (String [] args) throws FileNotFoundException {
        try {
            int counter = 0; // Counter for number of numbers in the txt file
            double sum = 0; // Sum of all digits in the txt file
            String line = null; // The line that is read in the txt file

            Scanner userIn = new Scanner(System.in);
            System.out.println("Type the name of the file located");
            String fileName = userIn.nextLine();
            BufferedReader in = new BufferedReader(new FileReader(Workbook1.txt));

            Object input;
            while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
                counter++;
                sum += Double.parseDouble(line);
            }

            double average = sum/counter;
            System.out.println("The average of the numbers is: " + format(average));
            System.out.println("The sum of the numbers is: " + sum);
            System.out.println("The number of digits is " + counter);
        }
        catch (IOException e) {
            System.out.println("Input/Output exception");
        }
    }

    public static String format(double number) {
        DecimalFormat d = new DecimalFormat("0.00");
        return d.format(number);
    }
}


有了这段代码,我遇到了一些错误。
这是显示的错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook1 cannot be resolved to a variable
The method hasNextLine() is undefined for the type BufferedReader
The method nextLine() is undefined for the type BufferedReader
at NumFile.NumFile.main(NumFile.java:27)


如果我删除:

Object input;
// Loop until the end of the file
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){


然后程序开始运行,但是找不到包含整数的.txt文件!

最佳答案

您可以执行以下操作:

Scanner in = new Scanner(new File(fileName));
String input = "";
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
    //code here
}

10-01 17:40