Exception in thread "main" java.lang.NumberFormatException: null

Exception in thread “main” java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:620)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at App14_1.main(App14_1.java:20)

运行程序时报错 java.lang.NumberFormatException: null,
一直以为是传参类型转换错误,通过查阅资料知也可以是获取不到参数(null)!

报错位置为:

  int[] num2 = new int[15];
            for(int i=0;i<15;i++){
                num2[i]=Integer.parseInt(in.readLine()); //error
            }
import java.io.*;
import java.util.Arrays;

public class App14_1 {
    public static void main(String[] args) throws IOException {
        try (
               BufferedReader in=new BufferedReader(new FileReader("F:/Java/aahh.txt"));
               BufferedWriter out = new BufferedWriter(new FileWriter("F:/Java/aahh.txt"));
        ) {

            int[] num1 = new int[15];
            for (int i = 0; i < num1.length; i++){
                num1[i] = (int) (Math.random() * 9979 + 20);
                out.write(num1[i]+"");
                out.newLine();
            }
           // out.close();   解决问题关键语句
            int[] num2 = new int[15];
            for(int i=0;i<15;i++){
                num2[i]=Integer.parseInt(in.readLine());
            }
            Arrays.sort(num2);
            for (int d : num2)
                System.out.println(d);
            }
        }
    }

解决问题:

缓冲字符输出流写入文件后未关闭流,导致输入流无法读取。
通过打印 in.readLine() 也可证明无法读取参数
在这里插入图片描述
于是 加入关闭流的语句,则问题解决。

小结

1、 java.lang.NumberFormatException: null,可以是传参类型转换错误,也可以是获取不到参数(null)!

2、对同一文件进行读写操作时 中间必须关闭流,或者用数组变量保存进而传递数据。(自动关闭资源语句得try语句结束后才关资源)

发布了23 篇原创文章 · 获赞 10 · 访问量 4992

猜你喜欢

转载自blog.csdn.net/Fzidx/article/details/104134450