Jason Brown
Jason Brown

Reputation: 59

Java parseInteger throwing error

I have the following code snippet from my tester class.

     FileReader freader=new FileReader(filename);
     BufferedReader inputFile=new BufferedReader(freader);
     int numScores = 0;
     String playerType = "";
     String nameHome = "";
     String playerName = "";
     String home = "";
     String location = "";
     int score = 0;
     String date = "";
     double courseRating = 0;
     int courseSlope = 0;

     ArrayList<Player> players = new ArrayList<Player>();

     while (inputFile.read()!= -1) {
        numScores = Integer.parseInt(inputFile.readLine()); 
        playerType = inputFile.readLine();
        nameHome = inputFile.readLine();
        StringTokenizer st = new StringTokenizer(nameHome,",");
        playerName = st.nextToken();
        home = st.nextToken();

The program compiles, however when the tester is run, I get the following output error.

Exception in thread "main" 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 PlayerTest.main(PlayerTest.java:34)

I've tried researching this and what I fould was there's possibly a space when it changes the String that is read from the data file and converts it to an int. I tried reading directly into a strin, trimming the string, then converting to the int, but it got the same error.

This was the code that replaced numScores = Integer.parseInt(inputFile.readLine());

        tempScores = inputFile.readLine();
           tempScores.trim();
           System.out.println(tempScores);
           numScores = Integer.parseInt(tempScores);

Any help is appreciated.

*edited to show sample data Sample data from file

3
B
James Smith, Strikers
FWB Bowling, 112,09/22/2012
White Sands, 142,09/24/2012
Cordova Lanes,203,09/24/2012

Upvotes: 0

Views: 321

Answers (4)

Luis Ramirez-Monterosa
Luis Ramirez-Monterosa

Reputation: 2242

I ran into a similar issue today. I was reading a response from REST end point and try to parse the json response. Bam! hit an error. Later on I realize the file had a BOM.

My suggestion is create a var

String var = inputFile.readLine();
int numScores = Integer.parseInt(var);

add a breakpoint and inspect what var contains, in my case the response had a BOM an empty unicode character code 65279 / 0xfeff. In any debugger worth it's salt you should be able to see each character.

if it's the case you need to strip that value from the string.

I used this library to detect this issue org.yaml:snakeyaml:1.16

import org.yaml.snakeyaml.reader.UnicodeReader;

//more code

  private String readStream(InputStream inputStream) throws IOException {
    UnicodeReader unicodeReader = new UnicodeReader(inputStream);
    char[] charBuffer = new char[BUFFER_SIZE];
    int read;
    StringBuilder buffer = new StringBuilder(BUFFER_SIZE);
    while ((read = unicodeReader.read(charBuffer,0,BUFFER_SIZE)) != -1) {
      buffer.append(charBuffer, 0, read);
    }
    return buffer.toString();
  }

Upvotes: 1

StackFlowed
StackFlowed

Reputation: 6816

You need to understand this please look into it.

Basic understanding is

try { 
   //Something that can throw an exception.
} catch (Exception e) {
  // To do whatever when the exception is caught.
} 

There is also an finally block which will always be execute even if there is an error. it is used like this

try { 
   //Something that can throw an exception.
} catch (Exception e) {
  // To do whatever when the exception is caught & the returned.
} finally {
  // This will always execute if there is an exception or no exception.
}

In your particular case you can have the following exceptions (link).

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed

So you would need to catch exceptions like

try { 
   rows=scan.nextInt();
} catch (InputMismatchException e) {
  // When the InputMismatchException is caught.
  System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
  // When the NoSuchElementException is caught.
  System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
  // When the IllegalStateException is caught.
  System.out.println("Scanner is close");
} 

Upvotes: 0

J Fabian Meier
J Fabian Meier

Reputation: 35795

Possibly, your File contains empty lines. These are read as "" and therefore cannot be converted to int.

Furthermore, it is possible that you read the first character of each line by the read-statement in the header of the while-loop, so that it is ignored in the readline command. Then a number of length 1 (like "1") would become an empty line.

In any case, the construction of your loop is a bug.

Upvotes: 3

brso05
brso05

Reputation: 13222

You can put it all in an if statement:

if(!tempScores.equalsIgnoreCase(""))
{

Upvotes: 1

Related Questions