NumberFormatException thrown by Integer.parseInt

情到浓时终转凉″ 提交于 2019-12-02 13:18:07

See, you are trying to parse "" as an Integer whichwill throw NumberFormatException. You have to check for null and isEmpty() in this order and then try to parse the string as an integer.

You are getting exception in this line , i think you are getting "" blank String from readLine() method

 end = (char) Integer.parseInt(entrada.readLine());

So Do like this

String input=entrada.readLine();
if(input!=null && !input.equals(""))
{
 end = (char) Integer.parseInt(input);
}

I suggest you to use google guava libraries which is having a utility function

Strings.isNullOrEmpty(inputString)//Checks String for both null and empty

Update As @ajb suggested :

If you want to convert s and n into character than don't use your code snippet

instead of Parsing an Integer

Use

char c=input.charAt(0);

you should replace continue statement with a break. putting continue will skip the current iteration and the while condition will not be evaluated.

This does not do what you think it will:

end = (char) Integer.parseInt(entrada.readLine());

This line reads a string. It then assumes the string is a number, and determines the number. If the user actually enters "s" or "n", it throws an exception, because "s" and "n" are not numbers. The number is then treated as the ASCII value of a character. The result is that the loop will test whether the user types in the string "110", since 110 is the ASCII value of the character n.

There are several ways to fix this; here's one:

end = entrada.readLine().charAt(0);

This returns the first character of whatever line the user types in. This is a sloppy solution because it doesn't work if the user hits ENTER on an empty line (it will throw an exception). Better:

String answer = entrada.readLine();  
if (answer.isEmpty()) {
    end = 'n';        // treat an empty string like 'n'
} else {
    end = answer.charAt(0);
}

Also, I think the while might be wrong. while (end == 'n') means the program will loop back if the user enters n, which I think is the opposite of what you want.

P.S. There are other errors that I didn't catch, that others have pointed out; using continue is wrong--use break to leave the switch statement. And reading one character with System.in.read() is a problem, because the user will type in a character, but the character won't get into the program until the user types ENTER, and then readLine() will get the rest of this first line, instead of asking for another line. But I usually don't use System.in.read() so I'm not completely sure what this does without trying it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!