I get: java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
when I try to use:
Integer.parseInt("h");
or
Integer.parseInt("h".toString());
but I was expecting it to work like atoi
in c.
What am I doing wrong here?
I get: java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
when I try to use:
Integer.parseInt("h");
or
Integer.parseInt("h".toString());
but I was expecting it to work like atoi
in c.
What am I doing wrong here?
The String
literal "h" obviously does not represent a valid integer.
Assuming h
is your String
variable, you don't need to use quotes:
String h = "1234";
Integer.parseInt(h);
Update: The function atoi returns an integer value of the input argument and returns zero if the input value is not valid. In Java, you could write this:
public static int javaAToI(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return 0;
}
}
This will only work if you parse it a String
that resembles Integer
.
You are parsing it a literal "h"
which can not be interpreted as Integer. If you parse it "123"
it will work.
Documentation of your method can be found here and documentation is usually a good place to start your search.
As someont else also suggested- if h
is your variable, parse it in this way: Integer.parseInt(h);
.
Edit:
If you want to convert a char
into int
, here is your answer: get char value in java
Java is doing exactly what it is supposed to here. In atoi
, when you are returned a 0, how do you know if your string contained a 0, or if it had a string that was not parsable? Java handles this by letting you know that you've tried to parse a string that doesn't contain a parsable value...ideally so you can go back and fix the code that is passing in an unparsable value.
In your case, if you wanted to handle the situation exactly like C does, you could just return a 0 if you catch a NumberFormatException. (It would probably be better if you could go back and ensure that you're not passing in bad strings, but that's not always possible.)