Can I read a string and then use it as an integer?

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?


Use Integer.valueOf:

int i = Integer.valueOf(someString);

(There are other options as well.)


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 string can'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!");
}

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

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 eg

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.

链接地址: http://www.djcxy.com/p/20914.html

上一篇: 将字符串值转换为int

下一篇: 我可以读取一个字符串,然后将其用作整数?