如何将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;
}
}
其他回答
这可以起作用,
Integer.parseInt(yourString);
手动执行:
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;
}
// As per your question "1234" → 1234
//using Integer.parseInt() method
public class StringToIntExample1{
public static void main(String args[]){
//Declaring String variable
String s="1234";
//Converting String into int using Integer.parseInt()
int i=Integer.parseInt(s);
//Printing value of i
System.out.println(i);
}
}
String myString = "1234";
int foo = Integer.parseInt(myString);
如果您查看Java文档,您会注意到“陷阱”是此函数可以引发NumberFormatException,您可以处理该异常:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
(此处理方法默认将格式错误的数字设置为0,但如果您愿意,可以执行其他操作。)
或者,您可以使用Guava库中的Ints方法,该方法与Java 8的Optional相结合,为将字符串转换为int提供了一种强大而简洁的方法:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
使用Java integer类的parseInt方法将字符串转换为整数。parseInt方法将字符串转换为int,如果字符串无法转换为int类型,则抛出NumberFormatException。
忽略它可能引发的异常,请使用以下命令:
int i = Integer.parseInt(myString);
如果变量myString表示的字符串是有效的整数,如“1234”、“200”、“1”,它将被转换为Java int。如果由于任何原因失败,则更改可能引发NumberFormatException,因此代码应该稍长一些才能解释这一点。
例如,Java String到int的转换方法,控制可能的NumberFormatException
public class JavaStringToIntExample
{
public static void main (String[] args)
{
// String s = "test"; // Use this if you want to test the exception below
String s = "1234";
try
{
// The String to int conversion happens here
int i = Integer.parseInt(s.trim());
// Print out the value after the conversion
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
如果更改尝试失败(在本例中,如果您可以尝试将Java String测试转换为int),Integer parseInt进程将抛出NumberFormatException,您必须在try/catch块中处理该异常。