Shantanu Nandan
Shantanu Nandan

Reputation: 1462

Trying to convert String to Integer

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)

Upvotes: 0

Views: 335

Answers (5)

Crystal Meth
Crystal Meth

Reputation: 589

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.

Upvotes: 0

Hars
Hars

Reputation: 169

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.

Upvotes: 0

Sean
Sean

Reputation: 62472

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.

Upvotes: 1

Tyler
Tyler

Reputation: 18177

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");

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93559

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.

Upvotes: 1

Related Questions