在Java中如何将字符串转换为int?

在Java中如何将字符串转换为int?,java,string,int,type-conversion,Java,String,Int,Type Conversion,如何在Java中将字符串转换为int 我的字符串只包含数字,我想返回它所代表的数字 例如,给定字符串“1234”,结果应该是数字1234 String myString = "1234"; int foo = Integer.parseInt(myString); 如果查看,您会注意到“catch”是该函数可以抛出一个NumberFormatException,当然您必须处理: int foo; try { foo = Integer.parseInt(myStrin

如何在Java中将
字符串
转换为
int

我的字符串只包含数字,我想返回它所代表的数字

例如,给定字符串
“1234”
,结果应该是数字
1234

String myString = "1234";
int foo = Integer.parseInt(myString);
如果查看,您会注意到“catch”是该函数可以抛出一个
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)

例如,这里有两种方法:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
这些方法之间有一点不同:

  • valueOf
    返回
    java.lang.Integer的新实例或缓存实例
  • parseInt
    返回原语
    int

<>所有的情况都是相同的:<代码>简短>值>代码> > SpSuthSuth, >Lo.Value> <代码> >代码> PARSELUN 等>

< P>。p> 在尝试从拆分参数获取整数值或动态解析某些内容时,处理此异常非常重要。

手动执行:

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;
}
publicstaticintstrotint(stringstr){
int i=0;
int num=0;
布尔值isNeg=false;
//检查是否有负号;如果有,则设置isNeg标志
如果(str.charAt(0)='-'){
isNeg=真;
i=1;
}
//处理字符串的每个字符;
而(i
您也可以先删除所有非数字字符,然后解析整数:

String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);
private static int parseInt(String str) {
    int i, n = 0;

    for (i = 0; i < str.length(); i++) {
        n *= 10;
        n += str.charAt(i) - 48;
    }
    return n;
}

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

将字符串转换为int比仅转换数字更复杂。您已经考虑了以下问题:

  • 字符串是否只包含数字0-9
  • 字符串前后的-/+是怎么回事?这可能吗(指会计数字)
  • MAX-/MIN\u INFINITY怎么了?如果字符串是999999999999999,会发生什么?机器能否将此字符串视为int

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

首先要做的是接收输入,在这种情况下,是一个数字串;我将其称为
stringnumber
,在本例中,我将使用数字12作为示例,因此
stringnumber=“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,我们不能做任何数学运算

我们以
2/10=0.2的方式将后一个数字(最后一位数字)除以10(因此为什么是双精度的),如下所示:

 lastdigit = lastdigit / 10;
这只是在玩弄数字。我们把最后一个数字变成了十进制。但现在,看看发生了什么:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2
不需要太多的数学知识,我们只是简单地将一个数字的单位分离出来。你看,因为我们只考虑0-9,除以10的倍数,就像创建一个“盒子”,在那里你储存它(回想一下当你的一年级老师解释你是一个单位和一百是什么)。因此:

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

  • 没有重复的循环
  • 没有像parseInt这样的“神奇”表达式

    • 我有一个解决方案,但我不知道它有多有效。但它工作得很好,我认为你可以改进它。另一方面,我做了两个测试,确定了正确的步骤。我附上了功能和测试:

      static public Integer str2Int(String str) {
          Integer result = null;
          if (null == str || 0 == str.length()) {
              return null;
          }
          try {
              result = Integer.parseInt(str);
          } 
          catch (NumberFormatException e) {
              String negativeMode = "";
              if(str.indexOf('-') != -1)
                  negativeMode = "-";
              str = str.replaceAll("-", "" );
              if (str.indexOf('.') != -1) {
                  str = str.substring(0, str.indexOf('.'));
                  if (str.length() == 0) {
                      return (Integer)0;
                  }
              }
              String strNum = str.replaceAll("[^\\d]", "" );
              if (0 == strNum.length()) {
                  return null;
              }
              result = Integer.parseInt(negativeMode + strNum);
          }
          return result;
      }
      
      使用JUnit进行测试:

      @Test
      public void testStr2Int() {
          assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
          assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
          assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
          assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
          assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
          assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
          assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
          assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
          assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
          assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
          assertEquals("Not
           is numeric", null, Helper.str2Int("czv.,xcvsa"));
          /**
           * Dynamic test
           */
          for(Integer num = 0; num < 1000; num++) {
              for(int spaces = 1; spaces < 6; spaces++) {
                  String numStr = String.format("%0"+spaces+"d", num);
                  Integer numNeg = num * -1;
                  assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
                  assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
              }
          }
      }
      
      @测试
      公共void testStr2Int(){
      assertEquals(“是数字的”,(整数)(-5),Helper.str2Int(-5”);
      assertEquals(“是数字的”,(整数)50,Helper.str2Int(“50.00”);
      assertEquals(“是数字的,(整数)20,Helper.str2Int($20.90”);
      assertEquals(“是数字的,(整数)5,Helper.str2Int(“5.321”);
      assertEquals(“是数字的”,(整数)1000,Helper.str2Int(“1000.50”);
      assertEquals(“是数字的”,(整数)0,Helper.str2Int(“0.50”);
      assertEquals(“是数字的,(整数)0,Helper.str2Int(.50”);
      assertEquals(“是数字的,(整数)0,Helper.str2Int(-.10”);
      assertEquals(“是数字的,(整数)Integer.MAX_值,Helper.str2Int(“+Integer.MAX_值”);
      assertEquals(“是数字的,(整数)Integer.MIN_值,Helper.str2Int(“+Integer.MIN_值”);
      资产质量(“非
      是数值型”,null,Helper.str2Int(“czv.,xcvsa”);
      /**
      *动态试验
      */
      对于(整数num=0;num<1000;num++){
      for(int空格=1;空格<6;空格++){
      String numStr=String.format(“%0”+空格+d”,num);
      整数numeng=num*-1;
      assertEquals(numStr+“:是数字的”,num,Helpe
      
      @Test
      public void testStr2Int() {
          assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
          assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
          assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
          assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
          assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
          assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
          assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
          assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
          assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
          assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
          assertEquals("Not
           is numeric", null, Helper.str2Int("czv.,xcvsa"));
          /**
           * Dynamic test
           */
          for(Integer num = 0; num < 1000; num++) {
              for(int spaces = 1; spaces < 6; spaces++) {
                  String numStr = String.format("%0"+spaces+"d", num);
                  Integer numNeg = num * -1;
                  assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
                  assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
              }
          }
      }
      
      int num = NumberUtils.toInt("1234");
      
      String strValue = "12345";
      Integer intValue = Integer.parseInt(strVal);
      
      String strValue = "12345";
      Integer intValue = Integer.valueOf(strValue);
      
      String strValue = "12345";
      Integer intValue = NumberUtils.toInt(strValue);
      
      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;
      }
      
      catch (NumberFormatException ex) {
          integerValue = 0;
      }
      
      // base 10
      Integer.parseInt("12");     // 12 - int
      Integer.valueOf("12");      // 12 - Integer
      Integer.decode("12");       // 12 - Integer
      // base 8
      // 10 (0,1,...,7,10,11,12)
      Integer.parseInt("12", 8);  // 10 - int
      Integer.valueOf("12", 8);   // 10 - Integer
      Integer.decode("012");      // 10 - Integer
      // base 16
      // 18 (0,1,...,F,10,11,12)
      Integer.parseInt("12",16);  // 18 - int
      Integer.valueOf("12",16);   // 18 - Integer
      Integer.decode("#12");      // 18 - Integer
      Integer.decode("0x12");     // 18 - Integer
      Integer.decode("0X12");     // 18 - Integer
      // base 2
      Integer.parseInt("11",2);   // 3 - int
      Integer.valueOf("11",2);    // 3 - Integer
      
      int val = Integer.decode("12"); 
      
      Integer.decode("12").intValue();
      
      private Optional<Integer> tryParseInteger(String string) {
          try {
              return Optional.of(Integer.valueOf(string));
          } catch (NumberFormatException e) {
              return Optional.empty();
          }
      }
      
      // prints "12"
      System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));
      // prints "-1"
      System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));
      // prints "invalid"
      System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));
      
      int foo = Integer.parseInt("1234");
      
      NumberUtils.toInt(String str, int defaultValue)
      
      NumberUtils.toInt("3244", 1) = 3244
      NumberUtils.toInt("", 1)     = 1
      NumberUtils.toInt(null, 5)   = 5
      NumberUtils.toInt("Hi", 6)   = 6
      NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
      NumberUtils.toInt(StringUtils.trimToEmpty("  32 ", 1)) = 32;
      
      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
      }
      
      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;
      }
      
      Integer fooInt = Ints.tryParse(fooString);
      if (fooInt != null) {
        ...
      }
      
      int number = Integer.parseInt("1234");
      
      Integer.parseInt(myBuilderOrBuffer.toString());
      
      String str = "1234";
      int number = Integer.parseInt(str);
      print number; // 1234
      
      private static int parseInt(String str) {
          int i, n = 0;
      
          for (i = 0; i < str.length(); i++) {
              n *= 10;
              n += str.charAt(i) - 48;
          }
          return n;
      }
      
      private static int parseInt(String str) {
          int i=0, n=0, sign=1;
          if (str.charAt(0) == '-') {
              i = 1;
              sign = -1;
          }
          for(; i<str.length(); i++) {
              n* = 10;
              n += str.charAt(i) - 48;
          }
          return sign*n;
      }
      
      String number = "10";
      int result = Integer.parseInt(number);
      System.out.println(result);
      
      String number = "10";
      Integer result = Integer.valueOf(number);
      System.out.println(result);
      
      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;
          }
      }
      
      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
      
      private void ConvertToInt(){
          String string = txtString.getText();
          try{
              int integerValue=Integer.parseInt(string);
              System.out.println(integerValue);
          }
          catch(Exception e){
             JOptionPane.showMessageDialog(
               "Error converting string to integer\n" + e.toString,
               "Error",
               JOptionPane.ERROR_MESSAGE);
          }
       }
      
      String myString = "1234";
      int i1 = new Integer(myString);
      
      public Integer(String var1) throws NumberFormatException {
          this.value = parseInt(var1, 10);
      }
      
      import com.google.common.primitives.Ints;
      import org.apache.commons.lang.math.NumberUtils;
      
      String number = "999";