whats wrong?(NumberFormatException: null)

前端 未结 4 1097
轮回少年
轮回少年 2020-12-18 09:37
    import java.io.*;
    class AccountInfo {

    private String lastName;
    private String firstName;
    private int age;
    private float accountBalance;
             


        
相关标签:
4条回答
  • 2020-12-18 10:06

    The br.readLine() method is returning null, which can't be converted into an Integer - the likely reason for this is that the end of the stream has been reached.

    0 讨论(0)
  • 2020-12-18 10:21

    This is your code:

    BufferedReader br=new BufferedReader(isr);
    //...
    age=Integer.parseInt(br.readLine());
    

    And here is the documentation of BufferedReader.readLine() (bold mine):

    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

    In fact, you never really check whether EOF was reached. Can you be that certain about your input (turns out you can't).

    Also for Integer.parseInt():

    Throws:

    NumberFormatException - if the string does not contain a parsable integer.

    null is hardly a "parsable integer". The simplest solution is to check your input and handle errors somehow:

    String ageStr = br.readLine();
    if(ageStr != null) {
      age = Integer.parseInt(br.readLine())
    } else {
      //decide what to do when end of file
    }
    
    0 讨论(0)
  • 2020-12-18 10:23

    From this line:

    Integer.parseInt(br.readLine());
    

    So it looks like you're reading the end of the stream so br.readLine() is null. And you can't parse null into an int.

    0 讨论(0)
  • 2020-12-18 10:26

    1. I think the value returned from br.readLine() is null.

    2. So it can NOT be converted from String to Integer.

    3. Thats the reason you are getting NumberFormatException

    4. To handle this, Wrap that code into try/catch block.

     try{
    
            age = Integer.parseInt(br.readLine());
    
    
      }catch(NumberFormatException ex){
    
    
            System.out.println("Error occured with during conversion");
     }
    
    0 讨论(0)
提交回复
热议问题