gpt4 book ai didi

java - 总和计算不正确

转载 作者:行者123 更新时间:2023-11-29 06:28:35 27 4
gpt4 key购买 nike

我正在尝试解决这个问题:

Write a Java program that reads a filename from the user. The file is expected to contain a maximum of 20 integers. Declare an array with the size 20. Read all the values from the file and store them in the array. Take note that there can be any number of integers in the file. Lastly, calculate and display the sum of all integers stored in the array. Use exception handling to detect:

  • Improper inputs from the file where a non-integer is read
  • Using of invalid array index
  • Invalid filename where he file does not exist

我目前的问题是总和不正确。这是我的代码

package labtask.pkg10;
import java.io.File;
import java.io.*;
import java.util.*;
import java.util.ArrayList;

public class task2 {
public static void main(String[] args) {
int integers[] = new int[20];
Scanner read = new Scanner(System.in);
int sum = 0;
int num = 0;
String filename;
System.out.println("enter the file name ");
filename = read.next();

try {
File file = new File(filename);
Scanner inputFile = null;
inputFile = new Scanner(file);

int i = 0;
while (inputFile.hasNext()) {
num = Integer.parseInt(inputFile.next());

integers[i] = num;
}

for (int x = 0; x < 20; x++) {
sum += num;
}
System.out.println("sum are : " + sum);
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (NumberFormatException e) {
System.out.println("please enter only integer number");
}
}
}

和我的文本文件:

2
2
2
2
2
2
2
2
2
12
23
2
2
2
2
2
2
2
2
2

我得到以下输出:

enter the file name
gg.txt
sum are : 40
BUILD SUCCESSFUL (total time: 2 seconds)

为什么总和数不对?

最佳答案

您将最后输入的数字相加 20 次,而不是将不同的数字相加。

将您的代码更改为:

while(inputFile.hasNext())
{
num = Integer.parseInt(inputFile.next());

integers[i++] = num;
}

for (int x = 0 ; x<integers.length; x ++)
{
sum += integers[x];
}

或者只使用一个循环:

while(inputFile.hasNext()) {
num = Integer.parseInt(inputFile.next());
integers[i++] = num;
sum += num;
}

关于java - 总和计算不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44631496/

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