使用扫描仪的.text文件中的数字平均值

时间:2014-04-09 18:48:32

标签: java while-loop java.util.scanner

我目前正在尝试创建一个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文件!

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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