[英]Java BufferedReader always throws a NumberFormatException for first Iteration
Why do I get the Not a number exception first and then get the correct output ? 为什么我先得到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);
}
}
The File contains numbers from 1 to 9 with each number in new line and there is no space or empty line in the beginning. 文件包含从1到9的数字,每个数字都换行,并且开头没有空格或空行。
Stacktrace prints the following exception 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
In your file , last line has a new line with \\n
i think . 在您的文件中 ,最后一行用
\\n
换行。 Be aware of end of file there is no new line. 请注意,文件末尾没有新行。 Check with counter or open file and delete last new line.
检查计数器或打开文件并删除最后一行。 That means file must be like this;
这意味着文件必须是这样的;
// -->remove all if some char is here!!
1\n
2\n
3\n
4\n
.
.
.
9 //--> there is no new line !!!!!
Or change your code ; 或更改您的代码;
if(line != null && !line.isEmpty()){
arr.add(Integer.parseInt(line.trim()));
}
It appears you have a blank line in your input. 看来输入中有空白行。 I suggest using
Scanner
instead as it skips the whitespace for you. 我建议改用
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.