如何将String转换为int?

"1234"  →  1234

当前回答

例如,这里有两种方法:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

这些方法略有不同:

valueOf返回java.lang.Integer的新实例或缓存实例parseInt返回基元int。

所有情况都是一样的:Short.valueOf/parseShort、Long.valueOf/parseLong等。

其他回答

您只需尝试以下操作:

使用Integer.parseInt(your_string);将字符串转换为int使用Double.parseDouble(your_string);将字符串转换为double

实例

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55

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

目前我正在做一项大学作业,在那里我不能使用某些表达式,例如上面的表达式,通过查看ASCII表,我成功地做到了这一点。这是一个复杂得多的代码,但它可以帮助像我一样受到限制的其他人。

首先要做的是接收输入,在本例中是一串数字;我将其称为String number,在本例中,我将使用数字12来举例说明,因此String number=“12”;

另一个限制是我不能使用重复的循环,因此,也不能使用for循环(这是完美的)。这限制了我们一点,但这也是我们的目标。由于我只需要两个数字(取最后两个数字),一个简单的charAt解决了这个问题:

 // Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length() - 2);
 int lastdigitASCII = number.charAt(number.length() - 1);

有了代码,我们只需要查看表格,并进行必要的调整:

 double semilastdigit = semilastdigitASCII - 48;  // A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

现在,为什么要加倍?嗯,因为一个非常“奇怪”的步骤。目前我们有两个双打,1和2,但我们需要将其转换为12,我们无法进行任何数学运算。

我们将后者(最后一个数字)除以10,以2/10=0.2的方式(因此为什么要加倍),如下所示:

 lastdigit = lastdigit / 10;

这只是在玩弄数字。我们正在把最后一位数字变成小数。但现在,看看会发生什么:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

没有太多的数学知识,我们只是简单地将数字的数字分离出来。你看,因为我们只考虑0-9,所以除以10的倍数就像创建一个“盒子”来存储它(回想一下一年级老师向你解释什么是单位和一百)。因此:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"

就这样。考虑到以下限制,您将数字字符串(在本例中为两个数字)转换为由这两个数字组成的整数:

无重复循环没有parseInt等“魔法”表达式

手动执行:

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;
}

这是一个完整的程序,所有条件都是正的和负的,不使用库

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;
    }
}