从文件中取出然后对整数求和但得到 0 作为答案

Taking from a file then summing the integers but getting 0 as answer

大家好,我有个问题。我正在尝试使用 hasNextInt() 对文件中的整数求和,但总和为 0。我找不到我的错误,请帮助我。

代码如下:

import java.io.*;
import java.util.*;

public class Number4 {

public static void main(String[] args) {
    Scanner square = null;

    try
    {
        square = new Scanner(new FileInputStream("Squares.txt"));
    }
    catch(Exception e)
    {
        System.out.print("File not found");
        System.exit(0);
    }

    String num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12,num13,num14,num15,num16,num17,num18,num19,num20;

    num1 = square.next();
    num2 = square.next();
    num3 = square.next();
    num4 = square.next();
    num5 = square.next();
    num6 = square.next();
    num7 = square.next();
    num8 = square.next();
    num9 = square.next();
    num10 = square.next();
    num11 = square.next();
    num12 = square.next();
    num13 = square.next();
    num14 = square.next();
    num15 = square.next();
    num16 = square.next();
    num17 = square.next();
    num18 = square.next();
    num19 = square.next();
    num20 = square.next();

    System.out.println(""+num1+"\n"+num2+"\n"+num3+"\n"+num4+"\n"+num5+"\n"+num6+"\n"+num7+"\n"+num8+"\n"+num9+"\n"+num10+num11+"\n"+num12+"\n"+num13+"\n"+num14+"\n"+num15+"\n"+num16+"\n"+num17+"\n"+num18+"\n"+num19+"\n"+num20);


    int next,sum = 0;

    while(square.hasNextInt())
    {
        next = square.nextInt();
        sum = next + sum; 
    }


    System.out.print("The sum is "+sum);
    square.close();

}

}

使用 square.next() 您在执行 square.nextInt() 时已经阅读了整个文件。在迭代的同时重新打开文件或写入 num*

如果您的文件中有 20 个数字,当您的代码到达:

next = square.nextInt();

什么也看不到,因为您已经阅读了 num# = square.next(); 行的整个文件。 (另请注意,您可以在文件中打印数字,这比您已经做的要简单得多。如果需要,您也可以计算此循环中的数字总和。像这样:

int sum = 0;
for (int i = 0; i < 20 && square.hasNextInt(); ++i) {
    int num = square.nextInt();
    sum += num;
    System.out.println(num);
}
System.out.print("The sum is " + sum);
square.close();

你的这个代码子集在做同样的事情。为什么要创建太多变量。简单地遍历文件中的所有整数,显示并求和。

 int next,sum = 0;

while(square.hasNextInt())
{
    next = square.nextInt();
    System.out.println(next+"\n");
    sum = next + sum; 
}