1

Possible Duplicate:
How to convert string to int in Java?

MY code is supposed to read strings and then take the corresponding actions, but if that string is a line of numbers i need this line as a full number (an int) not as a string anymore.can this be done?

0

3 Answers 3

7

Use Integer.valueOf:

int i = Integer.valueOf(someString);

(There are other options as well.)

Sign up to request clarification or add additional context in comments.

9 Comments

yup,that will do. Thanks
This will work, but has unnecessary boxing and unboxing. Better to use Integer.parseInt(...) for primitive int.
yep. As per the documentation, valueOf returns an Integer Object whereas parseInt returns a primitive int and that's what you want. (docs.oracle.com/javase/7/docs/api/java/lang/…)
It wasn't clear to me since the title said "integer" (but lower-case) and the text said "int". I find it unlikely the boxing is going to cause the OP timing issues.
It might not be a problem for the OP but it might be a problem for a future answer seeking coder. It should at least be mentioned when proposing the valueOf method.
|
3

Look at the static method Integer.parseInt(String string). This method is overloaded and is also capable of reading values in other numeral systems than the decimal system. If stringcan't be parsed as Integer, the method throws a NumberFormatException which can be catched as follows:

string = "1234"
try {
   int i = Integer.parseInt(string);
} catch (NumberFormatException e) {
   System.err.println(string + " is not a number!");
}

Comments

2

In addition to what Dave and wullxz said, you could also user regular expressions to find out if tested string matches your format e.g.

import java.util.regex.Pattern;
...

String value = "23423423";

if(Pattern.matches("^\\d+$", value)) {
   return Integer.valueOf(value);
}

Using regular expression you could also recover other type of numbers like doubles e.g.

String value = "23423423.33";
if(Pattern.matches("^\\d+$", value)) {
    System.out.println(Integer.valueOf(value));
}
else if(Pattern.matches("^\\d+\\.\\d+$", value)) {
    System.out.println(Double.valueOf(value));
}

I hope that will help to solve your problem.

EDIT

Also, as suggested by wullxz, you could use Integer.parseInt(String) instead of Integer.valueOf(String). parseInt returns int whereas valueOf returns Integer instance. From performance point of view parseInt is recommended.

2 Comments

I'd suggest you to change your use of valueOf to parseInt respectively parseDouble. (see the comments under Dave's answer)
@wullxz very good; from performance point of view that method is recommended (+1).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.