0

I am trying to generate a hashmap and require some of the strings from a textfile to be integers for the keys. However whenever I try to convert the string to integer the program crashes.

Here is the code below:

BufferedReader in = new BufferedReader(new FileReader("patient.txt"));//create thing to open the file
String line;
while((line = in.readLine())!= null)
{
    String[] text = line.split(",", -1);
    String keyString = text[0];
    String value = text[1] + text[2] + text[3] + text[4];
    int key = Integer.parseInt(keyString);
    System.out.println(key + " " + value);
}

The part that causes the program to crash is the parseInt line. I get the error

at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

Here's a sample of the text file. I am trying to convert Baker into an integer etc.

Baker, William,     Chavez,     04/01/05,   04/10/06
Sanchez, Jose,      Chavez,     06/15/05,
Andreas
  • 154,647
  • 11
  • 152
  • 247
Teemo
  • 35
  • 7
  • Catch `NumberFormatException`. – Shree Krishna May 04 '16 at 04:16
  • Possible duplicate of [How to resolve java.lang.NumberFormatException: For input string: "N/A"?](http://stackoverflow.com/questions/18711896/how-to-resolve-java-lang-numberformatexception-for-input-string-n-a) – Ankur Singhal May 04 '16 at 04:18
  • closing this, numberformatexception is very much clear, and nobody can do much here unless we have data, that is being passed – Ankur Singhal May 04 '16 at 04:18
  • I added a sample of the data from the textfile – Teemo May 04 '16 at 04:27
  • `42` is a number. `Baker` is not. What integer value were you even expecting `Baker` to become? – Andreas May 04 '16 at 04:29
  • I'm trying to make it whatever int it becomes – Teemo May 04 '16 at 04:30
  • Well, as you can see, it doesn't become an integer. Read the javadoc of [`Integer.parseInt()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29): *The characters in the string must all be **decimal digits***. – Andreas May 04 '16 at 04:35
  • There is no way to get a *unique* integer from a regular string, so why not just use the string as the key to the hashmap? – Andreas May 04 '16 at 04:36
  • The assignment is to use open addressing to make the hashmap and I don't know how to do it with string keys. – Teemo May 04 '16 at 13:52

2 Answers2

0

Handle this exception or Check if the string its really matching to number format:

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...
}
Stack Overflow
  • 2,416
  • 6
  • 23
  • 45
0

Your data does not allow that, if you look carefully into your code, you can see that String keyString = text[0]; is giving your "Baker" for the first line, which is not an integer.

nomadus
  • 859
  • 1
  • 12
  • 28