gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:59:55 24 4
gpt4 key购买 nike

大家好,我有个问题。我正在尝试使用 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.nextInt() 时,您已经使用 square.next() 读取了整个文件。在迭代的同时重新打开文件或写入 num*

关于java - 从文件中取出然后对整数求和但得到 0 作为答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27796875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com