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,
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!
...
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.