2017-10-11 9 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

関連する問題