Home > Software design >  It is throwing exception java.lang.NumberFormatException: Cannot parse null string?Why?
It is throwing exception java.lang.NumberFormatException: Cannot parse null string?Why?

Time:07-02

this is in main method I just Want to sum the numbers available in the text file located in E:\Java_Examples\data.txt.

int sum = 0;
        
        try {
            
             FileReader f1 = new FileReader("E:\\Java_Examples\\data.txt");

             BufferedReader s1=new BufferedReader(f1);
             String line="";
             while(s1.readLine()!=null)
             {
                 
                 line=s1.readLine();
                 sum =Integer.parseInt(line);
                 
             }
             s1.close();
          } catch(IOException e)
         {
             System.out.println("File not found");
          } 

Can anyone help with this?

CodePudding user response:

It is throwing exception java.lang.NumberFormatException: Cannot parse null string?Why?

Because you are calling readLine after the stream is empty.

Instead of this...

while(s1.readLine()!=null)
     {
         
         line=s1.readLine();
         sum =Integer.parseInt(line);
         
     }

You could do something like this...

while((line = s1.readLine())!=null)
     {
         
         sum =Integer.parseInt(line);
         
     }

CodePudding user response:

This sort of bug, and the large amount of code required for the simple task, happens when you write low-level code instead of using simpler approaches offered by the JDK.

Use Scanner:

int sum = 0;
    
Scanner scanner = new Scanner(new FileInputStream("E:/Java_Examples/data.txt"));
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    sum  = Integer.parseInt(line);
}

Or use Files for a one liner:

int sum = Files.lines(Paths.get("E:/Java_Examples/data.txt"))
  .mapToInt(Integer::parseInt)
  .sum();
  • Related