Search code examples
javaionumberformatexception

Java NumberFormatException Skip Line


I'm writing a program that reads in a list of numbers. Such as:

45
63
74g
34.7
75

I simply want my program to skip lines that contain any letters in them. Any help would be greatly appreciated. Thanks!

If it makes a difference, here is my code:

import java.io.*;

public class ScoreReader {

    public static void main(String[] args) {
        BufferedReader reader = null;

        try {
            String currentLine;

            reader = new BufferedReader(new FileReader("QuizScores.txt"));
            while ((currentLine = reader.readLine()) != null) {

                int sum = 0;

                String[] nums = currentLine.split("\\s+");
                for (int i = 0; i < nums.length; i++) {
                    int num = Integer.parseInt(nums[i]);
                    if (num != -1) {
                        sum += num;
                    }
                }

                System.out.println(sum / nums.length);
            }
        } catch (IOException err) {
            err.printStackTrace();
        } 
        catch (NumberFormatException err) {

        }

        finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException err) {
                err.printStackTrace();
            }
        }

    }
}

Solution

  • When an exception is thrown, execution jumps to the catch block. In what you have, this is after the loop, so the loop doesn't continue, just add a try around parseInt.

    try {
       String currentLine;
    
       reader = new BufferedReader(new FileReader("QuizScores.txt"));
       while ((currentLine = reader.readLine()) != null) {
    
           int sum = 0;
           String[] nums = currentLine.split("\\s+");
           for (int i = 0; i < nums.length; i++) {
               try{
                   int num = Integer.parseInt(nums[i]);
                   if (num != -1) {
                       sum += num;
                   }
               } catch( NumberFormatException nfe )
               {
                  // maybe log it?
               }
           }
    
           System.out.println(sum / nums.length);
       }
    } catch (IOException err) {
        err.printStackTrace();
    } 
    // catch (NumberFormatException err) {}
    finally {
        try {
           if (reader != null){
               reader.close();
        } catch (IOException err) {
            err.printStackTrace();
        }
    }
    

    Also note, you are using Integer.parseInt which will throw an exception with the input "34.7", so maybe you wish to use Double.parseDouble