如何找到文件中双打的平均值 - JAVA

时间:2013-10-17 04:33:45

标签: java

我需要跳过文本或整数。它读取一个.dat文件,其中包含数字(int / double)和字符串。它还计算并打印文件中的最大值,最小值,总和以及单词数。我该怎么做平均值?谢谢!!

import java.io.*;
import java.util.*;

public class ProcessFile {
public static void main(String [] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
    System.out.print("Enter file name: ");
    String n = console.next();
    File f = new File(n);
    while(!f.exists()){
        System.out.print("Doesn't exist. Enter a valid filename: ");
        n = console.next();
        f = new File(n);
    }
    Scanner input = new Scanner(f);

    int minInt = Integer.MAX_VALUE;
    int maxInt = Integer.MIN_VALUE;
    int countInt; 
    int averageInt =
    double minDouble = Double.MIN_VALUE;
    double maxDouble = Double.MAX_VALUE;
    double countDouble;
    double averageDouble = //sum / countDouble

    while(input.hasNext()){
        if (input.hasNextInt()){
            int next = input.nextInt();
            maxInt = Math.max(next, maxInt);
            minInt = Math.min(next, minInt);
            countIntC++;
            averageInt =                
            System.out.println("The results for the integers in the file :");
            System.out.printf(" Max = %d\n", maxInt);
            System.out.printf(" Min = %d\n", minInt);
            System.out.printf(" Count = %d\n", countInt);
            System.out.printf(" averageInt = %d\n", averageInt);


        } else if (input.hasNextDouble()) { //can I read it as a double
            double = next2 = input.nextDouble();
            maxDouble = Math.max(next2, maxDouble);
            minDouble = Math.min(next2, minDouble);
            countDouble++;
            averageDouble = 
            System.out.println("The results for the integers in the file:");
            System.out.printf(" Max = %f\n", maxDouble);
            System.out.printf(" Min = %f\n", minDouble);
            System.out.printf(" Count = %f\n", countDouble);
            System.out.printf(" averageInt = %f\n", averageDouble);

        } else { //it is String

        }               
    }
}

}

1 个答案:

答案 0 :(得分:1)

我看到三个问题

1) you need to initialize countDouble
   countDouble = 0;
   you're trying to do this countDouble++ before it's been ititialized

2) double = next2 = input.nextDouble();
   I believe should be this
   double next2 = input.nextDouble();

3) there no such variable countIntC
   you're trying to countIntC++
   should be countInt++

要计算,我想你想这样做

averageInt = (maxInt + minInt) / countInt; // I THINK, depending on your logic

总而言之,我感觉你的代码中有很多东西可以被抛弃。