I am trying to convert an string into int to see the result but i am getting runtime error.
String string="Java";
int see=Integer.parseInt("string");
and also tried for this code-
String[] sstring={"Java"};
int ssee=Interger.parseInt("sstring[0]");
and also tried for this code-
String[] sstring={"Java"};
int ssee=Interger.parseInt(sstring[0]);
Massage which I got-
Exception in thread "main" java.lang.NumberFormatException: For input string: "string"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at displayName.main(displayName.java:13)
-
Are u trying to print the ASCII numbers of the characters "Java"?anonymous– anonymous2014年02月15日 16:37:51 +00:00Commented Feb 15, 2014 at 16:37
-
1@anonymous No i was trying to see what happens if i tries to convert an string name into an integer but now i know that its impossible. How can i get the ASCII value of "Java"?Shantanu Nandan– Shantanu Nandan2014年02月15日 16:57:31 +00:00Commented Feb 15, 2014 at 16:57
-
@Shantanu: There is no way whatsoever to get the contents of the variable with the name corresponding to the contents of the string in Java.Louis Wasserman– Louis Wasserman2014年02月15日 17:13:44 +00:00Commented Feb 15, 2014 at 17:13
5 Answers 5
You need to give it a string containing an integer :
String value="10";
int x=Integer.parseInt(value);
If you don't pass in a valid string it will throw an exception when trying to parse, which is what you're seeing.
That's because there's no integer in that string. You have to pass it a number as a string for that to work, otherwise there's no valid value to return.
Depending on your use case, it may be perfectly ok to catch that exception and use a default value in this case.
This is an example of how the String#parseInt
is supposed to work
int see = Integer.parseInt("1234");
The string needs to represent a number.
Perhaps you're looking to get the ASCII value of the String?
String s = "Java";
byte[] bytes = s.getBytes("US-ASCII");
If you are looking for an Integer Object instead of the primitive type, you can use valueOf which returns
Integer i = Integer.valueOf("1234")
If you are new to Java try reading it here Difference between Integer and int.
Only numbers represented in the form of a String can be parsed using the Integer.parseInt()
function. In other cases the NumberFormatException
is thrown.
I would suggest Google and Wikipedia for simple things like these. They are a great source for learning and the first step towards solving simple doubts.
Hope this helped.