-1

I need to Skip over text or integers. It reads a .dat file that has numbers (int/doubles) and strings in it. It also Calculates and prints max, min, sum, and the count of the number of words in the file. How do I do the average? Thank you!!

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

        }               
    }
}

}

4

1 回答 1

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

总而言之,我感觉你的代码中发生了很多事情,可以扔掉。

于 2013-10-17T04:46:47.430 回答