对于我的任务,我要制作一个程序,从文本文件中读取和打印数字,然后计算这些数字的总和和平均值。我的程序做得很好。我唯一的问题是程序不会读取我的文本文件中的最后一个数字。文件上的数字为:
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
答案 0 :(得分: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++;
}