如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
正如我在GitHub上写的:
public class StringToInteger {
public static void main(String[] args) {
assert parseInt("123") == Integer.parseInt("123");
assert parseInt("-123") == Integer.parseInt("-123");
assert parseInt("0123") == Integer.parseInt("0123");
assert parseInt("+123") == Integer.parseInt("+123");
}
/**
* Parse a string to integer
*
* @param s the string
* @return the integer value represented by the argument in decimal.
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
*/
public static int parseInt(String s) {
if (s == null) {
throw new NumberFormatException("null");
}
boolean isNegative = s.charAt(0) == '-';
boolean isPositive = s.charAt(0) == '+';
int number = 0;
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
if (!Character.isDigit(s.charAt(i))) {
throw new NumberFormatException("s=" + s);
}
number = number * 10 + s.charAt(i) - '0';
}
return isNegative ? -number : number;
}
}
其他回答
int foo = Integer.parseInt("1234");
确保字符串中没有非数字数据。
整数代码
您还可以使用公共静态整数解码(Stringnm)抛出NumberFormatException。
它也适用于底座8和16:
// base 10
Integer.parseInt("12"); // 12 - int
Integer.valueOf("12"); // 12 - Integer
Integer.decode("12"); // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8); // 10 - int
Integer.valueOf("12", 8); // 10 - Integer
Integer.decode("012"); // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16); // 18 - int
Integer.valueOf("12",16); // 18 - Integer
Integer.decode("#12"); // 18 - Integer
Integer.decode("0x12"); // 18 - Integer
Integer.decode("0X12"); // 18 - Integer
// base 2
Integer.parseInt("11",2); // 3 - int
Integer.valueOf("11",2); // 3 - Integer
如果要获取int而不是Integer,可以使用:
取消装箱:int val=Integer.decode(“12”);intValue():Integer.decode(“12”).intValue();
自定义算法:
public static int toInt(String value) {
int output = 0;
boolean isFirstCharacter = true;
boolean isNegativeNumber = false;
byte bytes[] = value.getBytes();
for (int i = 0; i < bytes.length; i++) {
char c = (char) bytes[i];
if (!Character.isDigit(c)) {
isNegativeNumber = (c == '-');
if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
throw new NumberFormatException("For input string \"" + value + "\"");
}
} else {
int number = Character.getNumericValue(c);
output = output * 10 + number;
}
isFirstCharacter = false;
}
if (isNegativeNumber)
output *= -1;
return output;
}
另一种解决方案:
(使用string charAt方法,而不是将字符串转换为字节数组)
public static int toInt(String value) {
int output = 0;
boolean isFirstCharacter = true;
boolean isNegativeNumber = false;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (!Character.isDigit(c)) {
isNegativeNumber = (c == '-');
if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
throw new NumberFormatException("For input string \"" + value + "\"");
}
} else {
int number = Character.getNumericValue(c);
output = output * 10 + number;
}
isFirstCharacter = false;
}
if (isNegativeNumber)
output *= -1;
return output;
}
示例:
int number1 = toInt("20");
int number2 = toInt("-20");
int number3 = toInt("+20");
System.out.println("Numbers = " + number1 + ", " + number2 + ", " + number3);
try {
toInt("20 Hadi");
} catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
}
目前我正在做一项大学作业,在那里我不能使用某些表达式,例如上面的表达式,通过查看ASCII表,我成功地做到了这一点。这是一个复杂得多的代码,但它可以帮助像我一样受到限制的其他人。
首先要做的是接收输入,在本例中是一串数字;我将其称为String number,在本例中,我将使用数字12来举例说明,因此String number=“12”;
另一个限制是我不能使用重复的循环,因此,也不能使用for循环(这是完美的)。这限制了我们一点,但这也是我们的目标。由于我只需要两个数字(取最后两个数字),一个简单的charAt解决了这个问题:
// Obtaining the integer values of the char 1 and 2 in ASCII
int semilastdigitASCII = number.charAt(number.length() - 2);
int lastdigitASCII = number.charAt(number.length() - 1);
有了代码,我们只需要查看表格,并进行必要的调整:
double semilastdigit = semilastdigitASCII - 48; // A quick look, and -48 is the key
double lastdigit = lastdigitASCII - 48;
现在,为什么要加倍?嗯,因为一个非常“奇怪”的步骤。目前我们有两个双打,1和2,但我们需要将其转换为12,我们无法进行任何数学运算。
我们将后者(最后一个数字)除以10,以2/10=0.2的方式(因此为什么要加倍),如下所示:
lastdigit = lastdigit / 10;
这只是在玩弄数字。我们正在把最后一位数字变成小数。但现在,看看会发生什么:
double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2
没有太多的数学知识,我们只是简单地将数字的数字分离出来。你看,因为我们只考虑0-9,所以除以10的倍数就像创建一个“盒子”来存储它(回想一下一年级老师向你解释什么是单位和一百)。因此:
int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"
就这样。考虑到以下限制,您将数字字符串(在本例中为两个数字)转换为由这两个数字组成的整数:
无重复循环没有parseInt等“魔法”表达式
除了前面的答案,我还想添加几个功能。以下是使用时的结果:
public static void main(String[] args) {
System.out.println(parseIntOrDefault("123", 0)); // 123
System.out.println(parseIntOrDefault("aaa", 0)); // 0
System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}
实施:
public static int parseIntOrDefault(String value, int defaultValue) {
int result = defaultValue;
try {
result = Integer.parseInt(value);
}
catch (Exception e) {
}
return result;
}
public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
int result = defaultValue;
try {
String stringValue = value.substring(beginIndex);
result = Integer.parseInt(stringValue);
}
catch (Exception e) {
}
return result;
}
public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
int result = defaultValue;
try {
String stringValue = value.substring(beginIndex, endIndex);
result = Integer.parseInt(stringValue);
}
catch (Exception e) {
}
return result;
}