为什么我先得到Not a number异常,然后得到正确的输出?
import java.io.*;
import java.util.ArrayList;
public class readfile {
public static void main(String args[]) {
ArrayList<Integer> arr =new ArrayList<>();
BufferedReader buff = null;
FileInputStream fs = null;
try {
fs = new FileInputStream("/home/krishna/Documents/file/file");
buff = new BufferedReader(new InputStreamReader(fs));
String line = buff.readLine();
while(line != null) {
try {
arr.add(Integer.parseInt(line.trim()));
}
catch(NumberFormatException e) {
//System.out.println("Not a number");
e.printStackTrace();
}
line = buff.readLine();
}
}
catch(FileNotFoundException e) {
System.out.print(e);
}
catch(IOException e) {
System.out.print(e);
}
sumOfArray(arr);
}
static void sumOfArray(ArrayList<Integer> arr) {
int sum=0;
for(Integer a:arr) {
System.out.print(a+"\t");
sum = sum+a;
}
System.out.println("Sum is : "+" "+sum);
}
}
文件包含从1到9的数字,每个数字都换行,并且开头没有空格或空行。
Stacktrace打印以下异常
output:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.mojang.readfile.main(readfile.java:18)
1 2 3 4 5 6 7 8 9 Sum is : 45
答案 0 :(得分:1)
在您的文件中,我认为最后一行用\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()));
}
答案 1 :(得分:0)
似乎输入中有空白行。我建议改用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);
}
}