我怎样才能转换一个 String
到了 int
在Java?
我的字符串只包含数字,我想返回它代表的数字。
例如,给定字符串 "1234"
结果应该是数字 1234
。
我怎样才能转换一个 String
到了 int
在Java?
我的字符串只包含数字,我想返回它代表的数字。
例如,给定字符串 "1234"
结果应该是数字 1234
。
String myString = "1234";
int foo = Integer.parseInt(myString);
见 Java文档 了解更多信息。
String myString = "1234";
int foo = Integer.parseInt(myString);
见 Java文档 了解更多信息。
例如,有两种方法:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
这些方法之间略有不同:
valueOf
返回一个新的或缓存的实例 java.lang.Integer
parseInt
返回原语 int
。 所有情况都是如此: Short.valueOf
/parseShort
, Long.valueOf
/parseLong
等
好吧,需要考虑的一个非常重要的一点是Integer解析器抛出NumberFormatException,如中所述 的Javadoc。
int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。
手动完成:
public static int strToInt( String str ){
int i = 0;
int num = 0;
boolean isNeg = false;
//Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
//Process each character of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
目前我正在为大学做作业,在那里我不能使用某些表达式,例如上面的表达式,通过查看ASCII表,我设法做到了。这是一个复杂得多的代码,但它可以帮助像我一样受限制的其他代码。
首先要做的是接收输入,在这种情况下,是一串数字;我会叫它 String number
在这种情况下,我将使用数字12来举例说明 String number = "12";
另一个限制是我不能使用重复循环,因此,a 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,我们可以做任何数学运算。
我们将后者(lastdigit)除以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 "()"
你去吧考虑到以下限制,您将一个数字字符串(在本例中为两位数)转换为由这两个数字组成的整数:
另一种解决方案是使用 Apache Commons' NumberUtils:
int num = NumberUtils.toInt("1234");
Apache实用程序很好,因为如果字符串是无效的数字格式,则始终返回0。因此保存try catch块。
Integer.decode
你也可以使用 public static Integer decode(String nm) throws 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();
只要给定String不包含Integer的可能性最小,就必须处理这种特殊情况。可悲的是,标准的Java方法 Integer::parseInt
和 Integer::valueOf
抛出一个 NumberFormatException
发出这种特殊情况的信号。因此,您必须使用流控制的异常,这通常被认为是错误的编码风格。
在我看来,这个特殊情况应该通过返回来处理 Optional<Integer>
。由于Java不提供这样的方法,我使用以下包装器:
private Optional<Integer> tryParseInteger(String string) {
try {
return Optional.of(Integer.valueOf(string));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
用法:
// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));
虽然这仍然在内部使用流控制的异常,但使用代码变得非常干净。
将字符串转换为int比仅转换数字更复杂。您已经考虑过以下问题: