我怎么能转换String成intJava中?
我的字符串只包含数字,我想返回它表示的数字。
例如,给定字符串"1234"结果应该是数字1234。
StringmyString= "1234";
intfoo= Integer.parseInt(myString);
有关更多信息,请参阅Java文档。
例如,这里有两种方法:
Integerx= Integer.valueOf(str);
// or
inty= Integer.parseInt(str);
这些方法之间略有不同:
valueOf 返回一个新的或缓存的实例 java.lang.Integer
parseInt返回原始int。
所有情况也是如此:Short.valueOf/ parseShort,Long.valueOf/ parseLong等。
那么,需要考虑的一个非常重要的问题是Integer分析器抛出了Javadoc中所述的NumberFormatException异常。
intfoo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {foo= Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatExceptione) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {foo= Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatExceptione) {
//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.
}
尝试从split参数获取整数值或动态解析某些内容时处理此异常很重要。
手动操作:
public static intstrToInt( Stringstr){
inti= 0;
intnum= 0;
booleanisNeg= 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
}
if (isNeg)num= -num;
returnnum;
}
目前我正在为大学做作业,在那里我不能使用某些表达式,比如上面的表达式,通过查看ASCII表格,我设法做到了。这是一个非常复杂的代码,但它可以帮助像我一样受限制的其他人。
首先要做的是接收输入,在这种情况下是一串数字; 我会打电话给它String number,因此,在这种情况下,我将使用数字12来举例说明String number = "12";
另一个限制是我不能使用重复周期,因此,一个for周期(这将是完美的)也不能使用。这限制了我们一些,但是再一次,这就是目标。由于我只需要两位数字(取最后两位数字),一个简单的charAt解决方法就是:
// Obtaining the integer values of the char 1 and 2 in ASCII
intsemilastdigitASCII=number.charAt(number.length()-2);
intlastdigitASCII=number.charAt(number.length()-1);
有了代码,我们只需要查看表格并进行必要的调整:
doublesemilastdigit=semilastdigitASCII- 48; //A quick look, and -48 is the key
doublelastdigit=lastdigitASCII- 48;
现在,为什么要加倍?那么,因为一个非常“奇怪”的步骤。目前我们有两个双打,1和2,但我们需要把它变成12,没有任何我们可以做的数学运算。
我们以后者(lastdigit)除以10的方式2/10 = 0.2(因此为什么加倍)如下所示:
lastdigit=lastdigit/10;
这只是玩数字。我们将最后一位数字转成小数。但现在看看会发生什么:
doublejointdigits=semilastdigit+lastdigit; // 1.0 + 0.2 = 1.2
不用太深入数学,我们只是简单地将单位的数字隔开。你看,因为我们只考虑0-9,除以10的倍数就像创建一个存储它的“盒子”(回想一下你的一年级老师何时解释你是一个单位还是一百个单位)。所以:
intfinalnumber= (int) (jointdigits*10); // Be sure to use parentheses "()"
你去了。考虑到以下限制,您将一串数字(在本例中为两位数)转换为由这两位数组成的整数:
另一种解决方案是使用Apache Commons的 NumberUtils:
intnum= NumberUtils.toInt("1234");
Apache实用程序很好,因为如果字符串是无效的数字格式,则总是返回0。因此保存你的try catch块。