将字符串数转换为整数

Chr*_*iss 34 java

我将"1"作为字符串,我想将其转换为十进制1,作为整数.

我试过charAt(),但它返回49,而不是1整数.

那么,将"1"字符串转换为1整数需要什么?

KhA*_*aAb 25

使用包装类.

示例如下

INT

int a = Integer.parseInt("1"); // Outputs 1
Run Code Online (Sandbox Code Playgroud)

浮动

float a = Float.parseFloat("1"); // Outputs 1.0
Run Code Online (Sandbox Code Playgroud)

double a = Double.parseDouble("1"); // Outputs 1.0
Run Code Online (Sandbox Code Playgroud)

long a = Long.parseLong("1"); // Outputs 1
Run Code Online (Sandbox Code Playgroud)


Moo*_*oob 8

int one = Integer.parseInt("1");
Run Code Online (Sandbox Code Playgroud)

理想情况下,您也应该捕获错误:

int i;
String s = "might not be a number";
try {
   i = Integer.parseInt(s);
} catch (NumberFormatException e) {
   //do something
}
Run Code Online (Sandbox Code Playgroud)


fed*_*o-t 6

Integer.parseInt 就是这么做的.

int foo = Integer.parseInt("1");
Run Code Online (Sandbox Code Playgroud)