如何将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;
    }
}

其他回答

在编程竞赛中,如果您确信数字始终是有效的整数,那么您可以编写自己的方法来解析输入。这将跳过所有与验证相关的代码(因为您不需要任何代码),并且效率会更高一些。

对于有效的正整数:私有静态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()。

也可以从删除所有非数字字符开始,然后解析整数:

String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);

但请注意,这只适用于非负数。

对于Android开发者来说,以下是Kotlin的各种解决方案:

// Throws exception if number has bad form
val result1 = "1234".toInt()
// Will be null if number has bad form
val result2 = "1234"
    .runCatching(String::toInt)
    .getOrNull()
// Will be the given default if number has bad form
val result3 = "1234"
    .runCatching(String::toInt)
    .getOrDefault(0)
// Will be return of the else block if number has bad form
val result4 = "1234"
    .runCatching(String::toInt)
    .getOrElse {
        // some code
        // return an Int
    }

使用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块中处理该异常。

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)