0

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)
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Shantanu Nandan
  • 1,438
  • 8
  • 30
  • 56
  • Are u trying to print the ASCII numbers of the characters "Java"? – anonymous Feb 15 '14 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 Feb 15 '14 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 Feb 15 '14 at 17:13

5 Answers5

1

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.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
1

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.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

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");
Tyler
  • 17,669
  • 10
  • 51
  • 89
0

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.

Community
  • 1
  • 1
Hars
  • 169
  • 2
  • 12
0

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.

Crystal Meth
  • 589
  • 1
  • 4
  • 16