如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
这是一个完整的程序,所有条件都是正的和负的,不使用库
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("Not a Number");
}
else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
}
else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
}
else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
}
else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
}
else {
result = beforeDecimal;
}
return result * signBit;
}
}
其他回答
import java.util.*;
public class strToint {
public static void main(String[] args) {
String str = "123";
byte barr[] = str.getBytes();
System.out.println(Arrays.toString(barr));
int result = 0;
for(int i = 0; i < barr.length; i++) {
//System.out.print(barr[i]+" ");
int ii = barr[i];
char a = (char) ii;
int no = Character.getNumericValue(a);
result = result * 10 + no;
System.out.println(result);
}
System.out.println("result:"+result);
}
}
在编程竞赛中,如果您确信数字始终是有效的整数,那么您可以编写自己的方法来解析输入。这将跳过所有与验证相关的代码(因为您不需要任何代码),并且效率会更高一些。
对于有效的正整数:私有静态int parseInt(字符串str){整数i,n=0;对于(i=0;i<str.length();i++){n*=10;n+=str.charAt(i)-48;}返回n;}对于正整数和负整数:私有静态int parseInt(字符串str){int i=0,n=0,符号=1;if(str.charAt(0)==“-”){i=1;符号=-1;}对于(;i<str.length();i++){n*=10;n+=str.charAt(i)-48;}返回符号*n;}如果您希望在这些数字之前或之后有空格,然后确保在进一步处理之前执行str=str.trim()。
除了所有这些答案,我发现了一种新的方法,尽管它在内部使用Integer.parseInt()。
通过使用
import javafx.util.converter.IntegerStringConverter;
new IntegerStringConverter().fromString("1234").intValue()
or
new IntegerStringConverter().fromString("1234")
尽管随着新对象的创建,它的成本有点高。
只需浏览javafx.util.StringConverter<T>类。它有助于将任何包装器类值转换为字符串,反之亦然。
我有点惊讶,没有人提到将String作为参数的Integer构造函数。
因此,这里是:
String myString = "1234";
int i1 = new Integer(myString);
Java 8-整数(字符串)。
当然,构造函数将返回类型Integer,并且取消装箱操作将值转换为int。
注1:需要注意的是:此构造函数调用parseInt方法。
public Integer(String var1) throws NumberFormatException {
this.value = parseInt(var1, 10);
}
注2:已弃用:@deprecated(因为=“9”)-JavaDoc。
将String转换为Int的一些方法如下:
可以使用Integer.parseInt():字符串测试=“4568”;int new=Integer.parseInt(测试);也可以使用Integer.valueOf():字符串测试=“4568”;int new=Integer.valueOf(测试);