如何在 Java 中将一个字符串转换为一个 int 类型?

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

转载于:https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java

26个回答

String myString = "1234";
int foo = Integer.parseInt(myString);

See the Java Documentation for more information.

weixin_41568126
乱世@小熊 If you use Integer.parseInt prepare to put it inside a try catch block since this will throw are NumberFormat or InputMismatch Exception if it is not a valid number. Then in that case have proper exception handling at the catch block level. Otherwise as mentioned below you can also use the Integer class and then convert it to int.
接近 2 年之前 回复
csdnceshi64
游.程 This method also throws exception when string is not a parsable integer in base 10. Use overloaded method to work in other bases. e.g. Integer.parseInt("1001", 8); for base 8. Source.
大约 2 年之前 回复
csdnceshi65
larry*wei You could check if the string is a Number first: stackoverflow.com/questions/1102891/…
2 年多之前 回复
csdnceshi62
csdnceshi62 especially if using BIGINT field in a PostgreSQL auto incremented primary key field for instance. Much safer to use long
2 年多之前 回复
csdnceshi76
斗士狗 In addition to catching a NumberFormatException, the user should also be careful about the length of the strings they're passing in; if they're long enough to overflow an integer, they might want to consider using Long::parseLong instead.
2 年多之前 回复
weixin_41568131
10.24 This will throw NumberFormatException if input is not a valid number.
接近 5 年之前 回复

For example, here are two ways:

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

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

csdnceshi79
python小菜 thanks for the clarification.
接近 2 年之前 回复
weixin_41568183
零零乙 valueOf has two overloads - for int and String. valueOf(String) is implemented by first parsing the String to an int using parseInt(String) and then wrapping that int in an Integer by using valueOf(int). No recursion here because valueOf(String) and valueOf(int) are two completely different functions, even if they have the same name.
接近 2 年之前 回复
csdnceshi79
python小菜 i dont get it... valueOf calls itself recursively?
接近 2 年之前 回复
weixin_41568196
撒拉嘿哟木头 valueOf method is just return valueOf(parseInt(string));
接近 6 年之前 回复
csdnceshi71
Memor.の For the differences between the two methods, see this question
大约 7 年之前 回复

Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
}

try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
      //No problem this time, but still it is good practice to care about exceptions.
      //Never trust user input :)
      //Do something! Anything to handle the exception.
}

It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

csdnceshi63
elliott.david - See docs.oracle.com/javase/8/docs/api/java/util/regex/… - a regular expresssion pattern of "([0-9]+)" will "capture" the first sequence of one or more digits one through nine. Look at the Matcher class in that package.
大约 2 年之前 回复
csdnceshi78
程序go how can I parse "26263Hello" ? I want to extract 26263 in that case
大约 2 年之前 回复

Here we go

String str="1234";
int number = Integer.parseInt(str);
print number;//1234

This is Complete program with all conditions positive, negative without using library

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;
     }
    }
csdnceshi53
Lotus@ No, no one needs it because it is a function inside the JDK, not some third party plugin.
2 年多之前 回复
csdnceshi56
lrony* some people need this how to do without using Library.
2 年多之前 回复
csdnceshi53
Lotus@ I can see that, but what is the point not to use a library?
2 年多之前 回复
csdnceshi56
lrony* yes, we can do but this is without using library
2 年多之前 回复
csdnceshi53
Lotus@ There is no need to reinvent the wheel, just use Integer.parseInt.
2 年多之前 回复

Methods to do that:

 1. Integer.parseInt(s)
 2. Integer.parseInt(s, radix)
 3. Integer.parseInt(s, beginIndex, endIndex, radix)
 4. Integer.parseUnsignedInt(s)
 5. Integer.parseUnsignedInt(s, radix)
 6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
 7. Integer.valueOf(s)
 8. Integer.valueOf(s, radix)
 9. Integer.decode(s)
 10. NumberUtils.toInt(s)
 11. NumberUtils.toInt(s, defaultValue)

Integer.valueOf produces Integer object, all other methods - primitive int.

Last 2 methods from commons-lang3 and big article about converting here.

Apart from these above answers, I would like to add several functions:

    public static int parseIntOrDefault(String value, int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.parseInt(value);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex, endIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

And here are results while you running them:

  public static void main(String[] args) {
    System.out.println(parseIntOrDefault("123", 0)); // 123
    System.out.println(parseIntOrDefault("aaa", 0)); // 0
    System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
    System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
  }

You can use this code also, with some precautions.

  • Option #1: Handle the exception explicitly, for example, showing a message dialog and then stop the execution of the current workflow. For example:

    try
        {
            String stringValue = "1234";
    
            // From String to Integer
            int integerValue = Integer.valueOf(stringValue);
    
            // Or
            int integerValue = Integer.ParseInt(stringValue);
    
            // Now from integer to back into string
            stringValue = String.valueOf(integerValue);
        }
    catch (NumberFormatException ex) {
        //JOptionPane.showMessageDialog(frame, "Invalid input string!");
        System.out.println("Invalid input string!");
        return;
    }
    
  • Option #2: Reset the affected variable if the execution flow can continue in case of an exception. For example, with some modifications in the catch block

    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

Using a string constant for comparison or any sort of computing is always a good idea, because a constant never returns a null value.

csdnceshi55
~Onlooker Integer.valueOf(String); does not return type int.
4 年多之前 回复
csdnceshi75
衫裤跑路 Putting JOptionPane.showMessageDialog() in the answer to vanilla Java question makes no sense.
4 年多之前 回复

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

 // 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);

Having the codes, we just need to look up at the table, and make the necessary adjustments:

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

Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.

We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit/10;

This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

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

Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

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

And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No repetitive cycles
  • No "Magic" Expressions such as parseInt
csdnceshi77
狐狸.fox I was personally given that restriction when first starting out programming, and also when I had to write (pen/paper) similar interactions in a test. It's uncommon, but it's a method that is easily understood and while not being the most efficient by miles it's a method that works decently enough for small projects. SO.SE is meant to help everyone, not just a few. I provided an alternative method, for those who are starting out by learning how to create a pseudo-algorithm and turning it into an algorithm rather than using premade java expressions. Although I did forget that '0' is cool
4 年多之前 回复
csdnceshi54
hurriedly% It’s not clear what kind of problem this answer tries to solve, first, why anyone should ever have that restriction you describe, second, why you have to look at an ASCII table as you can simply use '0' for the character instead of 48 and never have to bother with its actual numeric value. Third, the entire detour with double values makes no sense at all as you are dividing by ten, just to multiply with ten afterwards. The result simply is semilastdigit * 10 + lastdigit as learnt in elementary school, when the decimal system was introduced…
4 年多之前 回复
csdnceshi69
YaoRaoLov Using type double for parsing an integer is not only a bad idea performance-wise. Values like 0.2 are periodic numbers in floating-point representation and cannot be represented precisely. Try System.out.println(0.1+0.2) to see the point -- the result will not be 0.3! Better stick with library code whereever you can, in this case Integer.parseInt().
接近 5 年之前 回复

Just for fun: You can use Java 8's Optional for converting a String into an Integer:

String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an NPE when str is null.

value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// Will do the same as the code above, except it will return -1
// when srt is null, instead of throwing an NPE.

Here we just combine Integer.valueOf and Optinal. Probably there might be situations when this is useful - for example when you want to avoid null checks. Pre Java 8 code will look like this:

Integer value = (str == null) ? -1 : Integer.parseInt(str);
weixin_41568126
乱世@小熊 return -1 in case of null looks really strange...what if I want to parse "-1" string?
大约 2 年之前 回复
csdnceshi54
hurriedly% Yes, it does. This code above is useless.
接近 3 年之前 回复
csdnceshi70
笑故挽风 If you ask me, it throws a NFE if you deliver an invalid Integer string ...
3 年多之前 回复
共26条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐