Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 323|回复: 0

[默认分类] How do I convert a String to an int in Java?

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-5-20 10:30:09 | 显示全部楼层 |阅读模式
    How can I convert a
    1. String
    复制代码
    to an
    1. int
    复制代码
    in java?
    如何将字符串转换成Java中的int类型?
    My String contains only numbers, and I want to return the number it represents.
    我的字符串只包含数字,我要返回它表示的数字。
    For example, given the string
    1. "1234"
    复制代码
    the result should be the number
    1. 1234
    复制代码
    .
    例如,给定字符串“1234”,结果应该是数字1234。30 个解决方案#1
    3420  
    1. [code]String myString = "1234";
    2. int foo = Integer.parseInt(myString);
    复制代码
    [/code]
    See the Java Documentation for more information.
    有关更多信息,请参见Java文档。#2
    561  For example, here are two ways:
    例如,这里有两种方法:
    1. [code]Integer x = Integer.valueOf(str);
    2. // or
    3. int y = Integer.parseInt(str);
    复制代码
    [/code]
    There is a slight difference between these methods:
    这些方法之间有细微的差别:

    1. valueOf
    复制代码
    returns a new or cached instance of
    1. java.lang.Integer
    复制代码
    valueOf返回一个新的或缓存的java.lang.Integer实例。
    1. parseInt
    复制代码
    returns primitive
    1. int
    复制代码
    .
    方法用于返回原始int。

    The same is for all cases:
    1. Short.valueOf
    复制代码
    /
    1. parseShort
    复制代码
    ,
    1. Long.valueOf
    复制代码
    /
    1. parseLong
    复制代码
    , etc.
    所有的情况都是一样的:短。返回对象的值/ parseShort,长。返回对象的值/ parseLong等等。#3
    204  Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.
    很重要的一点是,整数解析器会在Javadoc中抛出NumberFormatException。
    1. [code]int foo;
    2. String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
    3. String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
    4. try {
    5.       foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
    6. } catch (NumberFormatException e) {
    7.       //Will Throw exception!
    8.       //do something! anything to handle the exception.
    9. }
    10. try {
    11.       foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
    12. } catch (NumberFormatException e) {
    13.       //No problem this time, but still it is good practice to care about exceptions.
    14.       //Never trust user input :)
    15.       //Do something! Anything to handle the exception.
    16. }
    复制代码
    [/code]
    It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.
    在尝试从拆分参数或动态解析某些内容获取整数值时,处理这个异常是很重要的。#4
    70  Do it manually:
    手动启动:
    1. [code]public static int strToInt( String str ){
    2.     int i = 0;
    3.     int num = 0;
    4.     boolean isNeg = false;
    5.     //Check for negative sign; if it"s there, set the isNeg flag
    6.     if (str.charAt(0) == "-") {
    7.         isNeg = true;
    8.         i = 1;
    9.     }
    10.     //Process each character of the string;
    11.     while( i < str.length()) {
    12.         num *= 10;
    13.         num += str.charAt(i++) - "0"; //Minus the ASCII code of "0" to get the value of the charAt(i++).
    14.     }
    15.     if (isNeg)
    16.         num = -num;
    17.     return num;
    18. }
    复制代码
    [/code]#5
    34  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.
    目前我正在为大学做作业,在那里我不能使用某些表达式,比如上面的表达式,通过查看ASCII表,我成功地做到了这一点。这是一个复杂得多的代码,但它可以帮助像我这样受到限制的其他人。
    The first thing to do is to receive the input, in this case, a string of digits; I"ll call it
    1. String number
    复制代码
    , and in this case, I"ll exemplify it using the number 12, therefore
    1. String number = "12";
    复制代码
    首先要做的是接收输入,在这个例子中,是一串数字;我将它命名为String number,在这种情况下,我将用number 12来举例说明它,因此String number = "12";
    Another limitation was the fact that I couldn"t use repetitive cycles, therefore, a
    1. 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
    1. charAt
    复制代码
    solved it:
    另一个限制是,我不能使用重复周期,因此,for循环(本来应该是完美的)也不能使用。这限制了我们一点,但这是我们的目标。因为我只需要两个数字(最后两个数字),一个简单的查图解决了:
    1. [code] // Obtaining the integer values of the char 1 and 2 in ASCII
    2. int semilastdigitASCII = number.charAt(number.length()-2);
    3. int lastdigitASCII = number.charAt(number.length()-1);
    复制代码
    [/code]
    Having the codes, we just need to look up at the table, and make the necessary adjustments:
    有了这些代码,我们只需要查阅一下表格,做出必要的调整:
    1. [code] double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
    2. double lastdigit = lastdigitASCII - 48;
    复制代码
    [/code]
    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.
    为什么双?因为这是一个很奇怪的步骤。现在我们有两个双打,1和2,但是我们需要把它变成12,没有任何数学运算我们可以做。
    We"re dividing the latter (lastdigit) by 10 in the fashion
    1. 2/10 = 0.2
    复制代码
    (hence why double) like this:
    我们将后者(lastdigit)除以10,在时尚2/10 = 0.2(因此为什么是double):
    1. [code] lastdigit = lastdigit/10;
    复制代码
    [/code]
    This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:
    这只是在玩弄数字。我们把最后一位数变成了小数。但是现在,看看会发生什么:
    1. [code] double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2
    复制代码
    [/code]
    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:
    如果不考虑数学问题,我们只是简单地将一个数字的数字隔离开来。你看,因为我们只考虑0-9,除以10的倍数就像创建一个“盒子”,你把它储存起来(回想一下你的一年级老师给你解释了一个单位和100个是什么)。所以:
    1. [code] int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"
    复制代码
    [/code]
    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
    没有像parseInt这样的“魔法”表达式。
    #6
    32  An alternate solution is to use Apache Commons" NumberUtils:
    另一种解决方案是使用Apache Commons的NumberUtils:
    1. [code]int num = NumberUtils.toInt("1234");
    复制代码
    [/code]
    The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.
    Apache实用程序很好,因为如果字符串是无效的数字格式,那么总是返回0。因此,为您节省了try catch块。
    Apache NumberUtils API Version 3.4
    Apache NumberUtils API版本3.4。#7
    26  
    1. Integer.decode
    复制代码

    You can also use
    1. public static Integer decode(String nm) throws NumberFormatException
    复制代码
    .
    您还可以使用公共静态整数解码(String nm)抛出NumberFormatException。
    It also works for base 8 and 16:
    它也适用于8和16基地:
    1. [code]// base 10
    2. Integer.parseInt("12");     // 12 - int
    3. Integer.valueOf("12");      // 12 - Integer
    4. Integer.decode("12");       // 12 - Integer
    5. // base 8
    6. // 10 (0,1,...,7,10,11,12)
    7. Integer.parseInt("12", 8);  // 10 - int
    8. Integer.valueOf("12", 8);   // 10 - Integer
    9. Integer.decode("012");      // 10 - Integer
    10. // base 16
    11. // 18 (0,1,...,F,10,11,12)
    12. Integer.parseInt("12",16);  // 18 - int
    13. Integer.valueOf("12",16);   // 18 - Integer
    14. Integer.decode("#12");      // 18 - Integer
    15. Integer.decode("0x12");     // 18 - Integer
    16. Integer.decode("0X12");     // 18 - Integer
    17. // base 2
    18. Integer.parseInt("11",2);   // 3 - int
    19. Integer.valueOf("11",2);    // 3 - Integer
    复制代码
    [/code]
    If you want to get
    1. int
    复制代码
    instead of
    1. Integer
    复制代码
    you can use:
    如果你想要整数而不是整数,你可以使用:

    Unboxing:拆箱:
    1. [code]int val = Integer.decode("12");
    复制代码
    [/code]
    1. intValue()
    复制代码
    :intValue():
    1. [code]Integer.decode("12").intValue();
    复制代码
    [/code]
    #8
    19  Converting a string to an int is more complicated than just convertig a number. You have think about the following issues:
    将字符串转换为整数比仅仅转换一个数字要复杂得多。你可以考虑以下问题:

    Does the string only contains numbers 0-9?
    字符串是否只包含数字0-9?
    What"s up with -/+ before or after the string? Is that possible (referring to accounting numbers)?
    在字符串之前或之后是什么?这可能吗(指会计数字)?
    What"s up with MAX_-/MIN_INFINITY? What will happen if the string is 99999999999999999999? Can the machine treat this string as an int?
    与MAX_ / MIN_INFINITY是什么?如果字符串是9999999999999999,会发生什么?机器能把这条线当作整数吗?
    #9
    18  Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods
    1. Integer::parseInt
    复制代码
    and
    1. Integer::valueOf
    复制代码
    throw a
    1. NumberFormatException
    复制代码
    to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.
    无论何时,只要给定的字符串不包含整数,就必须处理这个特殊的情况。遗憾的是,标准的Java方法Integer::parseInt和Integer::valueOf抛出NumberFormatException来表示这个特殊的情况。因此,您必须使用流控制的异常,这通常被认为是糟糕的编码风格。
    In my opinion, this special case should be handled by returning an
    1. Optional<Integer>
    复制代码
    . Since Java does not offer such a method, I use the following wrapper:
    在我看来,这个特殊的情况应该通过返回一个可选的

      来处理。由于Java不提供这样的方法,所以我使用以下包装器:
      
    1. [code]private Optional<Integer> tryParseInteger(String string) {
    2.     try {
    3.         return Optional.of(Integer.valueOf(string));
    4.     } catch (NumberFormatException e) {
    5.         return Optional.empty();
    6.     }
    7. }
    复制代码
    [/code]
    Usage:
    用法:
    1. [code]// prints 1234
    2. System.out.println(tryParseInteger("1234").orElse(-1));
    3. // prints -1
    4. System.out.println(tryParseInteger("foobar").orElse(-1));
    复制代码
    [/code]
    While this is still using exceptions for flow control internally, the usage code becomes very clean.
    虽然这仍然在内部使用流控制的异常,但是使用代码变得非常干净。#10
    17  We can use the
    1. parseInt(String str)
    复制代码
    method of the
    1. Integer
    复制代码
    wrapper class for converting a String value to an integer value.
    我们可以使用整数包装器类的parseInt(String str)方法将字符串值转换为整数值。
    For example:
    例如:
    1. [code]String strValue = "12345";
    2. Integer intValue = Integer.parseInt(strVal);
    复制代码
    [/code]
    The
    1. Integer
    复制代码
    class also provides the
    1. valueOf(String str)
    复制代码
    method:
    整数类还提供了valueOf(String str)方法:
    1. [code]String strValue = "12345";
    2. Integer intValue = Integer.valueOf(strValue);
    复制代码
    [/code]
    We can also use
    1. toInt(String strValue)
    复制代码
    of NumberUtils Utility Class for the conversion:
    我们还可以使用NumberUtils实用程序类的toInt(String strValue)进行转换:
    1. [code]String strValue = "12345";
    2. Integer intValue = NumberUtils.toInt(strValue);
    复制代码
    [/code]#11
    15  I"m have a solution, but I do not know how effective it is. But it works well, and I think you could improve it. On the other hand, I did a couple of tests with JUnit which step correctly. I attached the function and testing:
    我有一个解决方案,但我不知道它有多有效。但是它很有效,我认为你可以改进它。另一方面,我用JUnit做了几个测试,这一步是正确的。我附加了功能和测试:
    1. [code]static public Integer str2Int(String str) {
    2.     Integer result = null;
    3.     if (null == str || 0 == str.length()) {
    4.         return null;
    5.     }
    6.     try {
    7.         result = Integer.parseInt(str);
    8.     }
    9.     catch (NumberFormatException e) {
    10.         String negativeMode = "";
    11.         if(str.indexOf("-") != -1)
    12.             negativeMode = "-";
    13.         str = str.replaceAll("-", "" );
    14.         if (str.indexOf(".") != -1) {
    15.             str = str.substring(0, str.indexOf("."));
    16.             if (str.length() == 0) {
    17.                 return (Integer)0;
    18.             }
    19.         }
    20.         String strNum = str.replaceAll("[^\\d]", "" );
    21.         if (0 == strNum.length()) {
    22.             return null;
    23.         }
    24.         result = Integer.parseInt(negativeMode + strNum);
    25.     }
    26.     return result;
    27. }
    复制代码
    [/code]
    Testing with JUnit:
    与JUnit测试:
    1. [code]@Test
    2. public void testStr2Int() {
    3.     assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
    4.     assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
    5.     assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
    6.     assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
    7.     assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
    8.     assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
    9.     assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
    10.     assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
    11.     assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
    12.     assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
    13.     assertEquals("Not
    14.      is numeric", null, Helper.str2Int("czv.,xcvsa"));
    15.     /**
    16.      * Dynamic test
    17.      */
    18.     for(Integer num = 0; num < 1000; num++) {
    19.         for(int spaces = 1; spaces < 6; spaces++) {
    20.             String numStr = String.format("%0"+spaces+"d", num);
    21.             Integer numNeg = num * -1;
    22.             assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
    23.             assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
    24.         }
    25.     }
    26. }
    复制代码
    [/code]#12
    11  Use
    1. Integer.parseInt(yourString)
    复制代码

    使用Integer.parseInt(yourString)
    Remember following things:
    记住以下事情:
    1. Integer.parseInt("1");
    复制代码
    // ok
    Integer.parseInt(" 1 ");/ /好吧
    1. Integer.parseInt("-1");
    复制代码
    // ok
    Integer.parseInt(" 1 ");/ /好吧
    1. Integer.parseInt("+1");
    复制代码
    // ok
    Integer.parseInt(“+ 1”);/ /好吧
    1. Integer.parseInt(" 1");
    复制代码
    // Exception (blank space)
    整数。方法(" 1 ");/ /异常(空白)
    1. Integer.parseInt("2147483648");
    复制代码
    // Exception (Integer is limited to a maximum value of 2,147,483,647)
    Integer.parseInt(“2147483648”);//例外(整数限为2,147,483,647)
    1. Integer.parseInt("1.1");
    复制代码
    // Exception (. or , or whatever is not allowed)
    Integer.parseInt(" 1.1 ");/ /异常(。或者,或者任何不允许的事情)
    1. Integer.parseInt("");
    复制代码
    // Exception (not 0 or something)
    Integer.parseInt(" ");//异常(非0或其他)
    There is only one type of exception:
    1. NumberFormatException
    复制代码

    只有一种类型的异常:NumberFormatException。#13
    10  Guava has tryParse(String), which returns
    1. null
    复制代码
    if the string couldn"t be parsed, for example:
    Guava有tryParse(String),如果字符串不能解析,则返回null,例如:
    1. [code]Integer fooInt = Ints.tryParse(fooString);
    2. if (fooInt != null) {
    3.   ...
    4. }
    复制代码
    [/code]#14
    10  Just for fun: You can use Java 8"s
    1. Optional
    复制代码
    for converting a
    1. String
    复制代码
    into an
    1. Integer
    复制代码
    :
    只是为了好玩:您可以使用Java 8的可选功能将字符串转换为整数:
    1. [code]String str = "123";
    2. Integer value = Optional.of(str).map(Integer::valueOf).get();
    3. // Will return the integer value of the specified string, or it
    4. // will throw an NPE when str is null.
    5. value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
    6. // Will do the same as the code above, except it will return -1
    7. // when srt is null, instead of throwing an NPE.
    复制代码
    [/code]
    Here we just combine
    1. Integer.valueOf
    复制代码
    and
    1. 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:
    这里我们把整数结合起来。返回对象的值和秦山核电。可能在某些情况下这是有用的——例如,当您想避免空检查时。Pre - Java 8代码如下:
    1. [code]Integer value = (str == null) ? -1 : Integer.parseInt(str);
    复制代码
    [/code]#15
    10  Methods to do that:
    方法:

    Integer.parseInt(s)
    Integer.parseInt(s)
    Integer.parseInt(s, radix)
    整数。方法(年代,基数)
    Integer.parseInt(s, beginIndex, endIndex, radix)
    整数。方法(s beginIndex endIndex基数)
    Integer.parseUnsignedInt(s)
    Integer.parseUnsignedInt(s)
    Integer.parseUnsignedInt(s, radix)
    整数。parseUnsignedInt(年代,基数)
    Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
    整数。parseUnsignedInt(s beginIndex endIndex基数)
    Integer.valueOf(s)
    Integer.valueOf(s)
    Integer.valueOf(s, radix)
    整数。返回对象的值(s,基数)
    Integer.decode(s)
    Integer.decode(s)
    NumberUtils.toInt(s)
    NumberUtils.toInt(s)
    NumberUtils.toInt(s, defaultValue)
    NumberUtils。defaultValue toInt(年代)

    Integer.valueOf produces Integer object, all other methods - primitive int.
    整数。valueOf产生整数对象,所有其他方法——原语int。
    Last 2 methods from commons-lang3 and big article about converting here.
    最后两种方法来自common -lang3和big article关于转换。#16
    9  You can also begin by removing all non-numerical characters and then parsing the int:
    您还可以首先删除所有非数字字符,然后解析int:
    1. [code]string mystr = mystr.replaceAll( "[^\\d]", "" );
    2. int number= Integer.parseInt(mystr);
    复制代码
    [/code]
    But be warned that this only works for non-negative numbers.
    但请注意,这只适用于非负数。#17
    8  Apart from these above answers, I would like to add several functions:
    除了以上这些答案,我还想补充几个功能:
    1. [code]    public static int parseIntOrDefault(String value, int defaultValue) {
    2.     int result = defaultValue;
    3.     try {
    4.       result = Integer.parseInt(value);
    5.     } catch (Exception e) {
    6.     }
    7.     return result;
    8.   }
    9.   public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
    10.     int result = defaultValue;
    11.     try {
    12.       String stringValue = value.substring(beginIndex);
    13.       result = Integer.parseInt(stringValue);
    14.     } catch (Exception e) {
    15.     }
    16.     return result;
    17.   }
    18.   public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
    19.     int result = defaultValue;
    20.     try {
    21.       String stringValue = value.substring(beginIndex, endIndex);
    22.       result = Integer.parseInt(stringValue);
    23.     } catch (Exception e) {
    24.     }
    25.     return result;
    26.   }
    复制代码
    [/code]
    And here are results while you running them:
    这里是你运行它们的结果:
    1. [code]  public static void main(String[] args) {
    2.     System.out.println(parseIntOrDefault("123", 0)); // 123
    3.     System.out.println(parseIntOrDefault("aaa", 0)); // 0
    4.     System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
    5.     System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
    6.   }
    复制代码
    [/code]#18
    6  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:选项#1:明确地处理异常,例如,显示一个消息对话框,然后停止当前工作流的执行。例如:
    1. [code]try
    2.     {
    3.         String stringValue = "1234";
    4.         // From String to Integer
    5.         int integerValue = Integer.valueOf(stringValue);
    6.         // Or
    7.         int integerValue = Integer.ParseInt(stringValue);
    8.         // Now from integer to back into string
    9.         stringValue = String.valueOf(integerValue);
    10.     }
    11. catch (NumberFormatException ex) {
    12.     //JOptionPane.showMessageDialog(frame, "Invalid input string!");
    13.     System.out.println("Invalid input string!");
    14.     return;
    15. }
    复制代码
    [/code]
    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选项#2:如果执行流可以在异常情况下继续,则重置受影响的变量。例如,在catch块中进行一些修改。
    1. [code]catch (NumberFormatException ex) {
    2.     integerValue = 0;
    3. }
    复制代码
    [/code]

    Using a string constant for comparison or any sort of computing is always a good idea, because a constant never returns a null value.
    使用字符串常量进行比较或任何类型的计算总是一个好主意,因为一个常量永远不会返回空值。#19
    6  As mentioned Apache Commons
    1. NumberUtils
    复制代码
    can do it. Which return
    1. 0
    复制代码
    if it cannot convert string to int.
    正如前面提到的,Apache Commons NumberUtils可以做到这一点。如果不能将字符串转换为int,则返回0。
    You can also define your own default value.
    您还可以定义自己的默认值。
    1. [code]NumberUtils.toInt(String str, int defaultValue)
    复制代码
    [/code]
    example:
    例子:
    1. [code]NumberUtils.toInt("3244", 1) = 3244
    2. NumberUtils.toInt("", 1)     = 1
    3. NumberUtils.toInt(null, 5)   = 5
    4. NumberUtils.toInt("Hi", 6)   = 6
    5. NumberUtils.toInt(" 32 ", 1) = 1 //space in numbers are not allowed
    6. NumberUtils.toInt(StringUtils.trimToEmpty( "  32 ",1)) = 32;
    复制代码
    [/code]#20
    6  You can use
    1. new Scanner("1244").nextInt()
    复制代码
    . Or ask if even an int exists:
    1. new Scanner("1244").hasNextInt()
    复制代码
    您可以使用新的扫描器(“1244”)。或者询问一个int是否存在:新的扫描器(“1244”)。#21
    4  In programming competitions, where you"re assured that number will always be a valid integer, then you can write your own method to parse input. This will skip all validation related code (since you don"t need any of that) and will be a bit more efficient.
    在编程竞赛中,您可以确保数字始终是一个有效的整数,然后您可以编写自己的方法来解析输入。这将跳过所有与验证相关的代码(因为您不需要这些代码),并且将会更加高效。

    For valid positive integer:有效的正整数:
    1. [code]private static int parseInt(String str) {
    2.     int i, n = 0;
    3.     for (i = 0; i < str.length(); i++) {
    4.         n *= 10;
    5.         n += str.charAt(i) - 48;
    6.     }
    7.     return n;
    8. }
    复制代码
    [/code]
    For both positive and negative integers:对于正整数和负整数:
    1. [code]private static int parseInt(String str) {
    2.     int i=0, n=0, sign=1;
    3.     if(str.charAt(0) == "-") {
    4.         i=1;
    5.         sign=-1;
    6.     }
    7.     for(; i<str.length(); i++) {
    8.         n*=10;
    9.         n+=str.charAt(i)-48;
    10.     }
    11.     return sign*n;
    12. }
    复制代码
    [/code]     
    If you are expecting a whitespace before or after these numbers, then make sure to do a
    1. str = str.trim()
    复制代码
    before processing further.如果您期望在这些数字之前或之后有一个空格,那么在进一步处理之前一定要做一个str = str.trim()。
    #22
    3  For normal string you can use:
    对于普通的字符串,您可以使用:
    1. [code]int number = Integer.parseInt("1234");
    复制代码
    [/code]
    For String builder and String buffer you can use:
    对于字符串生成器和字符串缓冲区,您可以使用:
    1. [code]Integer.parseInt(myBuilderOrBuffer.toString());
    复制代码
    [/code]#23
    3
    1. [code]int foo=Integer.parseInt("1234");
    复制代码
    [/code]
    Make sure there is no non-numeric data in the string.
    确保字符串中没有非数值数据。#24
    3  Here we go
    我们开始吧
    1. [code]String str="1234";
    2. int number = Integer.parseInt(str);
    3. print number;//1234
    复制代码
    [/code]#25
    2  Use Integer.parseInt() and put it inside a
    1. try...catch
    复制代码
    block to handle any errors just in case a non-numeric character is entered, for example,
    使用Integer.parseInt()并将其放入try…catch块处理任何错误,以防输入非数字字符,例如,
    1. [code]private void ConvertToInt(){
    2.     String string = txtString.getText();
    3.     try{
    4.         int integerValue=Integer.parseInt(string);
    5.         System.out.println(integerValue);
    6.     }
    7.     catch(Exception e){
    8.        JOptionPane.showMessageDialog(
    9.          "Error converting string to integer\n" + e.toString,
    10.          "Error",
    11.          JOptionPane.ERROR_MESSAGE);
    12.     }
    13. }
    复制代码
    [/code]#26
    2  Simply you can try this:
    你可以试试这个:

    Use
    1. Integer.parseInt(your_string);
    复制代码
    to convert a
    1. String
    复制代码
    to
    1. int
    复制代码
    使用Integer.parseInt(your_string);将字符串转换为整数。
    Use
    1. Double.parseDouble(your_string);
    复制代码
    to convert a
    1. String
    复制代码
    to
    1. double
    复制代码
    使用Double.parseDouble(your_string);将字符串转换为double。

    Example
    1. [code]String str = "8955";
    2. int q = Integer.parseInt(str);
    3. System.out.println("Output>>> " + q); // Output: 8955
    复制代码
    [/code]

    1. [code]String str = "89.55";
    2. double q = Double.parseDouble(str);
    3. System.out.println("Output>>> " + q); // Output: 89.55
    复制代码
    [/code]#27
    1  One method is parseInt(String) returns a primitive int
    一个方法是parseInt(String)返回一个原语int。
    1. [code]String number = "10";
    2. int result = Integer.parseInt(number);
    3. System.out.println(result);
    复制代码
    [/code]
    Second method is valueOf(String) returns a new Integer() object.
    第二个方法是valueOf(String)返回一个新的Integer()对象。
    1. [code]String number = "10";
    2. Integer result = Integer.valueOf(number);
    3. System.out.println(result);
    复制代码
    [/code]#28
    1  This is Complete program with all conditions positive, negative without using library
    这是一个完整的程序,所有的条件都是积极的,否定的,不使用图书馆。
    1. [code]import java.util.Scanner;
    2.     public class StringToInt {
    3.      public static void main(String args[]) {
    4.       String inputString;
    5.       Scanner s = new Scanner(System.in);
    6.       inputString = s.nextLine();
    7.       if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
    8.        System.out.println("Not a Number");
    9.       } else {
    10.        Double result2 = getNumber(inputString);
    11.        System.out.println("result = " + result2);
    12.       }
    13.      }
    14.      public static Double getNumber(String number) {
    15.       Double result = 0.0;
    16.       Double beforeDecimal = 0.0;
    17.       Double afterDecimal = 0.0;
    18.       Double afterDecimalCount = 0.0;
    19.       int signBit = 1;
    20.       boolean flag = false;
    21.       int count = number.length();
    22.       if (number.charAt(0) == "-") {
    23.        signBit = -1;
    24.        flag = true;
    25.       } else if (number.charAt(0) == "+") {
    26.        flag = true;
    27.       }
    28.       for (int i = 0; i < count; i++) {
    29.        if (flag && i == 0) {
    30.         continue;
    31.        }
    32.        if (afterDecimalCount == 0.0) {
    33.         if (number.charAt(i) - "." == 0) {
    34.          afterDecimalCount++;
    35.         } else {
    36.          beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - "0");
    37.         }
    38.        } else {
    39.         afterDecimal = afterDecimal * 10 + number.charAt(i) - ("0");
    40.         afterDecimalCount = afterDecimalCount * 10;
    41.        }
    42.       }
    43.       if (afterDecimalCount != 0.0) {
    44.        afterDecimal = afterDecimal / afterDecimalCount;
    45.        result = beforeDecimal + afterDecimal;
    46.       } else {
    47.        result = beforeDecimal;
    48.       }
    49.       return result * signBit;
    50.      }
    51.     }
    复制代码
    [/code]#29
    0  Use this line to parse a string value to int:
    使用这一行来将字符串值解析为int:
    1. [code] String x = "11111111";
    2. int y = Integer.parseInt(x);
    3. System.out.println(y);
    复制代码
    [/code]#30
    -6  Alternatively, you can use Integer.valueOf(). It will return an
    1. Integer
    复制代码
    object.
    或者,您也可以使用Integer.valueOf()。它将返回一个整数对象。
    1. [code]String numberStringFormat = "10";
    2. Integer resultIntFormat = Integer.valueOf(numberStringFormat);
    3. LOG.info("result:"+result);
    复制代码
    [/code]
    Output:
    10
    10
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-16 19:09 , Processed in 0.428990 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表