2 回答
TA贡献1942条经验 获得超3个赞
在您的文件中,\n我认为最后一行有一个新行。请注意文件末尾没有新行。检查计数器或打开文件并删除最后一行。这意味着文件必须是这样的;
// -->remove all if some char is here!!
1\n
2\n
3\n
4\n
.
.
.
9 //--> there is no new line !!!!!
或更改您的代码;
if(line != null && !line.isEmpty()){
arr.add(Integer.parseInt(line.trim()));
}
TA贡献1887条经验 获得超5个赞
您的输入中似乎有一个空行。我建议Scanner改用它,因为它会为您跳过空格。
public class ReadFile {
public static void main(String[] args) throws IOException {
String file = "/home/krishna/Documents/file/file";
List<Integer> ints = new ArrayList<>();
try (Scanner in = new Scanner(new File(file))) {
while (in.hasNextInt())
ints.add(in.nextInt());
}
sumOfArray(ints);
}
static void sumOfArray(List<Integer> ints) {
long sum = 0;
for (int a : ints) {
System.out.print(a + "\t");
sum += a;
}
System.out.println("\nSum is: " + sum);
}
}
添加回答
举报