为了账号安全,请及时绑定邮箱和手机立即绑定

Java BufferedReader 总是在第一次迭代时抛出

Java BufferedReader 总是在第一次迭代时抛出

慕盖茨4494581 2021-10-27 17:02:45
为什么我先得到 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
查看完整描述

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()));

}


查看完整回答
反对 回复 2021-10-27
?
慕工程0101907

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);

    }

}


查看完整回答
反对 回复 2021-10-27
  • 2 回答
  • 0 关注
  • 141 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信