Java 计算机未从文本文件中读取最后一个数字
我的任务是制作一个程序,从文本文件中读取并打印数字,然后计算这些数字的总和和平均值。我的程序做得很好。我唯一的问题是程序无法从我的文本文件中读取最后一个数字。文件上的数字为:Java 计算机未从文本文件中读取最后一个数字,java,Java,我的任务是制作一个程序,从文本文件中读取并打印数字,然后计算这些数字的总和和平均值。我的程序做得很好。我唯一的问题是程序无法从我的文本文件中读取最后一个数字。文件上的数字为: 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.prin
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
程序读取最后一个数字,但不使用它, 看看这部分: 最后一个数字已被读取,但从未添加到
总和中
您需要对语句重新排序:
while (inFile.hasNext()) {
int num = inFile.nextInt();
System.out.println(num);
sum += num;
numberAmount++;
}
这管用!多谢各位
while (inFile.hasNext()) {
int num = inFile.nextInt();
System.out.println(num);
sum += num;
numberAmount++;
}