首先要做的是接收输入,在这种情况下,是一串数字;我将其称为 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;
String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an NPE when str is null.
value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// Will do the same as the code above, except it will return -1
// when srt is null, instead of throwing an NPE.
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.
}
尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要 .
6
手动完成:
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;
}
3
你可以使用 new Scanner("1244").nextInt() . 或者询问是否存在int: new Scanner("1244").hasNextInt()
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;
}
try
{
String stringValue = "1234";
// From String to Integer
int integerValue = Integer.valueOf(stringValue);
// Or
int integerValue = Integer.ParseInt(stringValue);
// Now from integer to back into string
stringValue = String.valueOf(integerValue);
}
catch (NumberFormatException ex) {
//JOptionPane.showMessageDialog(frame, "Invalid input string!");
System.out.println("Invalid input string!");
return;
}
30 回答
Guava有tryParse(String),如果无法解析字符串,则返回
null
,例如:顺便提一下,请注意,如果字符串为null,则调用:
抛出NumberFormatException,而不是NullPointerException .
有关更多信息,请参见Java Documentation .
在编程竞赛中,您可以确保数字始终是有效整数,那么您可以编写自己的方法来解析输入 . 这将跳过所有与验证相关的代码(因为您不需要任何相关代码)并且会更有效率 .
str = str.trim()
.我有点意外,没有人提到将String作为参数的Integer构造函数 .
所以,这是:
Java 8 - Integer(String) .
当然,构造函数将返回
Integer
类型,并且取消装箱操作会将值转换为int
.值得一提的是
此构造函数调用
parseInt
方法 .例如,有两种方法:
这些方法之间略有不同:
valueOf
返回java.lang.Integer
的新缓存实例parseInt
返回原始int
.所有情况都是如此:
Short.valueOf
/parseShort
,Long.valueOf
/parseLong
等 .Integer.decode
你也可以使用
public static Integer decode(String nm) throws NumberFormatException
.它也适用于基数8和16:
如果你想得到
int
而不是Integer
你可以使用:intValue()
:方法:
Integer.valueOf生成Integer对象,所有其他方法 - primitive int .
来自commons-lang3的最后2个方法和关于转换here的大文章 .
我们可以使用
Integer
包装类的parseInt(String str)
方法将String值转换为整数值 .例如:
Integer
类还提供了valueOf(String str)
方法:我们也可以使用
toInt(String strValue)
的NumberUtils Utility Class进行转换:你可以试试这个:
使用
Integer.parseInt(your_string);
将String
转换为int
使用
Double.parseDouble(your_string);
将String
转换为double
示例
一种方法是parseInt(String)返回一个原语int
第二种方法是valueOf(String)返回一个新的Integer()对象 .
目前我正在为大学做作业,在那里我不能使用某些表达式,例如上面的表达式,通过查看ASCII表,我设法做到了 . 这是一个复杂得多的代码,但它可以帮助像我一样受限制的其他代码 .
首先要做的是接收输入,在这种情况下,是一串数字;我将其称为
String number
,在这种情况下,我将使用数字12来举例说明,因此String number = "12";
另一个限制是我无法使用重复循环,因此,
for
循环(本来是完美的)可以实现目标 . 由于我只需要两位数(取最后两位数字),一个简单的charAt
解决了它:有了代码,我们只需要查看表格,并进行必要的调整:
现在,为什么加倍?好吧,因为一个非常“奇怪”的步骤 . 目前我们有两个双打,1和2,但是我们需要把它变成12,我们可以做任何数学运算 .
我们将后者(lastdigit)除以时尚
2/10 = 0.2
(因此为什么加倍)这样:这只是玩数字 . 我们把最后一位数字变成了小数 . 但现在,看看会发生什么:
没有太多的数学,我们只是将数字与数字隔离 . 你看,因为我们只考虑0-9,除以10的倍数就像创建一个存储它的“盒子”(当你的一年级老师解释你是一个单位和一百个是什么时,回想一下) . 所以:
你去吧考虑到以下限制,您将一个数字字符串(在本例中为两位数)转换为由这两个数字组成的整数:
没有重复循环
否"Magic"表达式如parseInt
使用Integer.parseInt(yourString)
Remember following things:
Integer.parseInt("1");
//好的Integer.parseInt("-1");
//好的Integer.parseInt("+1");
//好的Integer.parseInt(" 1");
//异常(空格)Integer.parseInt("2147483648");
//异常(整数仅限于maximum value,2,147,483,647)Integer.parseInt("1.1");
//异常( . 或 , 或其他不允许的内容)Integer.parseInt("");
//异常(不是0或者什么)只有一种类型的例外:NumberFormatException
您也可以先删除所有非数字字符,然后解析int:
但请注意,这仅适用于非负数 .
使用Integer.parseInt()并将其放在
try...catch
块中以处理任何错误,以防万一输入非数字字符,例如,对于普通字符串,您可以使用:
对于String builder和String buffer,您可以使用:
只是为了好玩:你可以使用Java 8的
Optional
将String
转换为Integer
:这里我们只结合
Integer.valueOf
和Optinal
. 可能存在这种情况有用的情况 - 例如,当您想要避免空检查时 . Pre Java 8代码如下所示:另一种解决方案是使用Apache Commons' NumberUtils:
Apache实用程序很好,因为如果字符串是无效的数字格式,则始终返回0 . 因此保存try catch块 .
Apache NumberUtils API Version 3.4
This is Complete program with all conditions positive, negative without using library
好吧,需要考虑的一个非常重要的一点是,整数解析器抛出了Javadoc中所述的NumberFormatException .
尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要 .
手动完成:
你可以使用
new Scanner("1244").nextInt()
. 或者询问是否存在int:new Scanner("1244").hasNextInt()
只要给定String不包含Integer的可能性最小,就必须处理这种特殊情况 . 遗憾的是,标准的Java方法
Integer::parseInt
和Integer::valueOf
抛出一个NumberFormatException
来表示这种特殊情况 . 因此,您必须使用流控制的异常,这通常被认为是错误的编码风格 .在我看来,这个特殊情况应该通过返回
Optional<Integer>
来处理 . 由于Java不提供这样的方法,我使用以下包装器:用法:
虽然这仍然在内部使用流控制的异常,但使用代码变得非常干净 .
如前所述,Apache Commons
NumberUtils
可以做到 . 如果它不能将字符串转换为int,则返回0
.您还可以定义自己的默认值 .
例:
将字符串转换为int比仅转换数字更复杂 . 您已经考虑过以下问题:
字符串是否只包含数字 0-9 ?
字符串之前或之后的 -/+ 是什么?这是可能的(指会计数字)?
怎么了 MAX_-/MIN_INFINITY? 如果字符串是99999999999999999999会怎么样?机器可以将此字符串视为int吗?
除了以上这些答案,我想添加几个功能:
以下是运行它们时的结果:
您也可以使用此代码,并采取一些预防措施 .
使用字符串常量进行比较或任何类型的计算总是一个好主意,因为常量永远不会返回空值 .
开始了
我有一个解决方案,但我不知道它有多有效 . 但它运作良好,我认为你可以改善它 . 另一方面,我用JUnit进行了几次测试,这是正确的 . 我附上了功能和测试:
使用JUnit进行测试:
确保字符串中没有非数字数据 .