我希望将字符串转换为整数,以便我可以要求用户输入,然后相应地倒计时。
代码:
String bottle = "bottles";
String num = "";
request.getParameter(bottles);
int number = bottles;
最佳答案
我将使用 Integer.parseInt
并将 try
/catch
括在 NumberFormatException
中(输入 String
不代表整数)。
我还会添加一个空检查,以防您无法控制正在解析的String
。
// null check
if (bottles != null) {
try {
int foo = Integer.parseInt(bottles);
}
catch (NumberFormatException nfe) {
// bottles does not represent an integer
nfe.printStackTrace();
}
}
关于java - Java 将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22099081/