2017-10-11 41 views
3

對於我的任務,我製作了一個程序,用於讀取和打印文本文件中的數字,然後計算這些數字的總和和平均值。我的程序做得很好。我唯一的問題是,該程序不會從我的文本文件中讀取最後一個數字。在該文件中的數字閱讀:計算機沒有讀取文本文件中的最後一個數字

3 
8 
1 
13 
18 
15 
7 
17 
1 
14 
0 
12 
3 
2 
5 
4 

出於某種原因,計算機將無法讀取數字4

這裏是我的程序:

{ //begin testshell 
public static void main (String[] args) 
{ //begin main 
    System.out.println("Scores"); 
    Scanner inFile=null; 
    try 
    { 
     inFile = new Scanner(new File("ints.dat")); 
    } 
    catch (FileNotFoundException e) 
     { 
     System.out.println ("File not found!"); 
     // Stop program if no file found 
     System.exit (0); 
     } 

    // sets sum at 0 so numbers will be added 
    int sum=0; 

    int num= inFile.nextInt(); 

    // starts counting the amount of numbers so average can be calculated 
    int numberAmount=0; 

    while(inFile.hasNext()) 
    {  
     // print the integer 
     System.out.println(num); 

     // adds the number to 0 and stores the new number into the variable sum 
     sum = num+sum; 

     // increases the number of numbers 
     numberAmount++; 
     // reads the next integer 
     num = inFile.nextInt(); 
    } 
    inFile.close(); 
    // calculates average 
    double average = (double)sum/(double)numberAmount; 
    average = Math.round (average * 100.0)/100.0; 

    //output 
    System.out.println("The sum of the numbers = "+sum); 
    System.out.println("The number of scores = "+numberAmount); 
    System.out.println("The average of the numbers = "+average); 

    }//end main 
}//end testshell 

回答

6

程序讀取最後一個號碼,但它不使用它, 看看這個部分:

while(inFile.hasNext()) 
{  
    // ... 
    sum = num+sum; 

    // reads the next integer 
    num = inFile.nextInt(); 
} 

最後一個數字被讀取,但從未添加到sum

您需要重新排列聲明:

while (inFile.hasNext()) {  
    int num = inFile.nextInt(); 

    System.out.println(num); 

    sum += num; 

    numberAmount++; 
} 
+0

這個作品!非常感謝 – lyah

相關問題