我正试图解决这个问题:
编写一个从用户读取文件名的Java程序.该文件最多包含20个整数.声明一个大小为20的数组.读取文件中的所有值并将它们存储在数组中.请注意,文件中可以包含任意数量的整数.最后,计算并显示存储在数组中的所有整数的总和.使用异常处理来检测:
- 来自文件的不正确输入,其中读取非整数
- 使用无效数组索引
- 文件不存在的文件名无效
我目前的问题是错误的总和.这是我的代码
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
和我的文字文件:
2
2
2
2
2
2
2
2
2
12
23
2
2
2
2
2
2
2
2
2
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
输入文件名
gg.txt
总和是:40
BUILD SUCCESSFUL(总时间:2秒)
为什么总和不算正确?
您将最后一个输入添加到总和20次而不是添加不同的数字.
将您的代码更改为:
while(inputFile.hasNext())
{
num = Integer.parseInt(inputFile.next());
integers[i++] = num;
}
for (int x = 0 ; x<integers.length; x ++)
{
sum += integers[x];
}
Run Code Online (Sandbox Code Playgroud)
或者只使用一个循环:
while(inputFile.hasNext()) {
num = Integer.parseInt(inputFile.next());
integers[i++] = num;
sum += num;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
329 次 |
| 最近记录: |