2013-10-17 42 views
-1

我需要跳過文本或整數。它讀取一個包含數字(int/double)和字符串的.dat文件。它還計算並打印文件中最大值,最小值,總和和單詞數量的計數。我如何做平均?謝謝!!如何找到文件中雙打的平均值 - JAVA

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

你究竟在哪裏卡住了?我看到的只是你的任務和一些代碼。如果你花點功夫爲我們描述更多關於你的問題,這將是很好的。 –

+3

你必須計算它。 –

+1

我在這裏看到一個很大的問題'雙= NEXT2 = input.nextDouble();' –

回答

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 

所有的一切,我有一種感覺,有很多繼續在你的代碼中,可以拋出。

+0

謝謝!這真的有幫助。自原始帖子以來,我編輯了很多我的代碼。這似乎是我正在尋找,但! – Jessica