ฉันจะแปลง a Stringเป็นintin Java ได้อย่างไร?
My String มีตัวเลขเท่านั้นและฉันต้องการคืนค่าที่เป็นตัวแทน
ตัวอย่างเช่นกำหนดสตริงผลที่ควรจะเป็นจำนวน"1234"1234
ฉันจะแปลง a Stringเป็นintin Java ได้อย่างไร?
My String มีตัวเลขเท่านั้นและฉันต้องการคืนค่าที่เป็นตัวแทน
ตัวอย่างเช่นกำหนดสตริงผลที่ควรจะเป็นจำนวน"1234"1234
คำตอบ:
String myString = "1234";
int foo = Integer.parseInt(myString);
หากคุณดูเอกสาร Javaคุณจะสังเกตเห็นว่า "catch" คือฟังก์ชันนี้สามารถโยน a NumberFormatExceptionซึ่งแน่นอนว่าคุณต้องจัดการ:
int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}
(การรักษานี้ใช้ค่าเริ่มต้นเป็นจำนวนที่ผิดรูปแบบ0แต่คุณสามารถทำอย่างอื่นได้หากต้องการ)
หรือคุณสามารถใช้Intsวิธีการจากไลบรารี Guava ซึ่งใช้ร่วมกับ Java 8's Optionalทำให้เป็นวิธีที่มีประสิทธิภาพและรัดกุมในการแปลงสตริงเป็น int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)
              int foo = NumberUtils.toInt(myString, 0);
                    ตัวอย่างเช่นต่อไปนี้เป็นสองวิธี:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
มีความแตกต่างเล็กน้อยระหว่างวิธีการเหล่านี้:
valueOf ส่งคืนอินสแตนซ์ใหม่หรือแคชของ java.lang.IntegerparseIntintผลตอบแทนดั้งเดิมเช่นเดียวกันสำหรับทุกกรณี: Short.valueOf/ parseShort, Long.valueOf/ parseLong, ฯลฯ
valueOfวิธีการเป็นเพียงreturn valueOf(parseInt(string));
                    valueOfเรียกตัวเองซ้ำแล้วซ้ำอีก?
                    valueOf(String)ถูกนำมาใช้เป็นครั้งแรกโดยการแยกสตริงเป็น int ใช้parseInt(String)แล้วห่อ int valueOf(int)ว่าในจำนวนเต็มโดยใช้ ไม่มีการเรียกซ้ำที่นี่เพราะvalueOf(String)และvalueOf(int)เป็นสองฟังก์ชันที่แตกต่างอย่างสิ้นเชิงแม้ว่าพวกเขาจะมีชื่อเดียวกัน
                    ดีเป็นจุดสำคัญมากที่จะต้องพิจารณาก็คือการแยกวิเคราะห์จำนวนเต็มโยน NumberFormatException ตามที่ระบุไว้ใน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.
}
มันเป็นสิ่งสำคัญที่จะจัดการกับข้อยกเว้นนี้เมื่อพยายามรับค่าจำนวนเต็มจากการขัดแย้งแบบแยกหรือแยกบางอย่างแบบไดนามิก
"([0-9]+)"จะ "จับ" ลำดับแรกของตัวเลขหนึ่งหลักหรือมากกว่าหนึ่งถึงเก้า ดูMatcherคลาสในแพ็คเกจนั้น
                    ทำด้วยตนเอง:
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;
}
              Integer.parseInt(s)? - ฉันเห็นประเด็นเกี่ยวกับเรื่องนี้เป็นคำถามสัมภาษณ์ แต่ก) ไม่ได้หมายความว่าคุณจะทำแบบนี้ (ซึ่งเป็นสิ่งที่ผู้ถามถาม) และข) คำตอบนี้เป็นตัวอย่างที่ไม่ดีเลย
                    Integer.parseInt เพราะไม่มีการตรวจสอบ
                    ทางเลือกอื่นคือใช้NumberUtils ของ Apache Commons :
int num = NumberUtils.toInt("1234");
ยูทิลิตี้ Apache ดีเพราะถ้าสตริงเป็นรูปแบบตัวเลขที่ไม่ถูกต้อง 0 จะถูกส่งกลับเสมอ ดังนั้นช่วยให้คุณประหยัดบล็อคลอง
ขณะนี้ฉันกำลังทำงานที่ได้รับมอบหมายให้เรียนที่ฉันไม่สามารถใช้นิพจน์บางอย่างเช่นรายการด้านบนและโดยการดูตาราง 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 ไม่มีการดำเนินการทางคณิตศาสตร์ใด ๆ ที่เราสามารถทำได้
เราแบ่งส่วนหลัง (lastdigit) เป็น 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 "()"
และคุณไป คุณเปลี่ยนสตริงของตัวเลข (ในกรณีนี้คือตัวเลขสองหลัก) เป็นจำนวนเต็มซึ่งประกอบด้วยตัวเลขสองหลักโดยพิจารณาถึงข้อ จำกัด ดังต่อไปนี้:
'0'สำหรับตัวละครแทน48และไม่ต้อง รำคาญกับค่าตัวเลขที่แท้จริง ประการที่สามอ้อมทั้งหมดที่มีdoubleค่าไม่สมเหตุสมผลเลยในขณะที่คุณหารด้วยสิบเพียงคูณด้วยสิบหลังจากนั้น ผลที่ได้ก็จะsemilastdigit * 10 + lastdigitเป็นเรียนรู้ในโรงเรียนประถมศึกษาเมื่อระบบทศนิยมได้รับการแนะนำ ...
                    semilastdigit lastdigitคุณจะเขียนโค้ดโซลูชันของคุณเพื่อหลีกเลี่ยง "วงจรวนซ้ำ" ได้อย่างไรถ้าฉันให้สตริงตัวเลขที่ถูกต้องซึ่งมีความยาวตามอำเภอใจ (เช่นค่าใด ๆ ระหว่าง "-2147483648" และ "2147483647")
                    Integer.decodepublic static Integer decode(String nm) throws NumberFormatExceptionนอกจากนี้คุณยังสามารถใช้
นอกจากนี้ยังใช้งานได้กับฐาน 8 และ 16:
// 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แทนคุณIntegerสามารถใช้:
unboxing:
int val = Integer.decode("12"); intValue():
Integer.decode("12").intValue();เมื่อใดก็ตามที่มีความเป็นไปได้น้อยที่สุดที่สตริงที่กำหนดไม่มีจำนวนเต็มคุณต้องจัดการกับกรณีพิเศษนี้ เศร้า Java วิธีมาตรฐานInteger::parseIntและInteger::valueOfโยนNumberFormatExceptionเพื่อส่งสัญญาณในกรณีพิเศษนี้ ดังนั้นคุณต้องใช้ข้อยกเว้นสำหรับการควบคุมการไหลซึ่งโดยทั่วไปถือว่าเป็นรูปแบบการเข้ารหัสที่ไม่ดี
Optional<Integer>ในความคิดของกรณีพิเศษนี้ควรได้รับการจัดการโดยการกลับว่างเปล่า เนื่องจาก Java ไม่มีวิธีดังกล่าวฉันจึงใช้ wrapper ต่อไปนี้:
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"));
ขณะนี้ยังคงใช้ข้อยกเว้นสำหรับการควบคุมการไหลภายในรหัสการใช้งานจะสะอาดมาก นอกจากนี้คุณสามารถแยกแยะกรณีและปัญหาได้อย่างชัดเจนว่า-1มีการแยกวิเคราะห์เป็นค่าที่ถูกต้องและกรณีที่ไม่สามารถแยกวิเคราะห์สตริงที่ไม่ถูกต้อง
การแปลงสตริงเป็น int มีความซับซ้อนมากกว่าเพียงแค่แปลงตัวเลข คุณคิดถึงปัญหาต่อไปนี้:
วิธีการที่จะทำเช่นนั้น:
 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 สร้างวัตถุจำนวนเต็มวิธีอื่นทั้งหมด - ดั้งเดิม int
ล่าสุด 2 วิธีจากคอมมอน-lang3และบทความเกี่ยวกับการแปลงขนาดใหญ่ที่นี่
เราสามารถใช้parseInt(String str)วิธีการของIntegerคลาส wrapper สำหรับการแปลงค่า String เป็นค่าจำนวนเต็ม
ตัวอย่างเช่น:
String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);
Integerชั้นนอกจากนี้ยังมีvalueOf(String str)วิธีการ:
String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);
นอกจากนี้เรายังสามารถใช้toInt(String strValue)ของNumberUtils ยูทิลิตี้ชั้นสำหรับการแปลง:
String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
              Integer.parseInt(yourString)ใช้
จำสิ่งต่อไปนี้:
Integer.parseInt("1");      // ตกลง
Integer.parseInt("-1");     // ตกลง
Integer.parseInt("+1");     // ตกลง
Integer.parseInt(" 1");     // ข้อยกเว้น (พื้นที่ว่าง)
Integer.parseInt("2147483648");// ข้อยกเว้น (จำนวนเต็มถูก จำกัด ไว้ที่ค่าสูงสุดที่ 2,147,483,647)
Integer.parseInt("1.1");// ข้อยกเว้น ( .หรือ,หรืออะไรก็ตามที่ไม่ได้รับอนุญาต)
Integer.parseInt(""); // ข้อยกเว้น (ไม่ใช่ 0 หรือบางอย่าง)
มีข้อยกเว้นเพียงประเภทเดียวเท่านั้น: NumberFormatException
ฉันมีวิธีแก้ปัญหา แต่ฉันไม่รู้ว่ามันมีประสิทธิภาพแค่ไหน แต่มันใช้งานได้ดีและฉันคิดว่าคุณสามารถปรับปรุงได้ ในทางกลับกันฉันได้ทำการทดสอบสองครั้งกับJUnitซึ่งเป็นขั้นตอนที่ถูกต้อง ฉันแนบฟังก์ชั่นและการทดสอบ:
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));
        }
    }
}
              (int) Double.parseDouble(input.replaceAll("[^0-9\\.\\-]", ""));
                    Google GuavaมีtryParse (String)ซึ่งจะส่งคืนnullหากไม่สามารถแยกสตริงได้เช่น:
Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}
              คุณสามารถเริ่มต้นด้วยการลบอักขระที่ไม่ใช่ตัวเลขทั้งหมดแล้วแยกวิเคราะห์จำนวนเต็ม:
String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);
แต่ได้รับคำเตือนว่าวิธีนี้ใช้ได้กับหมายเลขที่ไม่เป็นลบเท่านั้น
"4+2"ฉันจะได้รับ42ผลลัพธ์โดยไม่มีการบอกใบ้ว่าสิ่งที่ฉันพยายามทำนั้นถูกเข้าใจผิด ผู้ใช้จะได้รับการแสดงผลที่ป้อนการแสดงออกพื้นฐานเช่น4+2เป็นอินพุตที่ถูกต้อง แต่แอปพลิเคชันยังคงมีค่าที่ไม่ถูกต้อง นอกจากนั้นประเภทคือStringไม่string...
                    นอกเหนือจากคำตอบก่อนหน้านี้ฉันต้องการเพิ่มฟังก์ชั่นหลายอย่าง นี่คือผลลัพธ์ในขณะที่คุณใช้งาน:
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;
}
              ตามที่กล่าวไว้ Apache Commons NumberUtilsสามารถทำได้ มันจะส่งกลับ0ถ้ามันไม่สามารถแปลงสตริงเป็น int
คุณยังสามารถกำหนดค่าเริ่มต้นของคุณเอง:
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;
              คุณสามารถใช้รหัสนี้ได้ด้วยความระมัดระวัง
ตัวเลือก # 1: จัดการข้อยกเว้นอย่างชัดเจนเช่นการแสดงข้อความโต้ตอบและหยุดการทำงานของกระแสงานปัจจุบัน ตัวอย่างเช่น:
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;
}ตัวเลือก # 2: รีเซ็ตตัวแปรที่ได้รับผลกระทบหากโฟลว์การดำเนินการสามารถดำเนินการต่อในกรณีที่มีข้อยกเว้น ตัวอย่างเช่นการแก้ไขบางอย่างใน catch block
catch (NumberFormatException ex) {
    integerValue = 0;
}การใช้ค่าคงที่สตริงสำหรับการเปรียบเทียบหรือการคำนวณประเภทใด ๆ เป็นความคิดที่ดีเสมอเพราะค่าคงที่จะไม่ส่งคืนค่า Null
JOptionPane.showMessageDialog()คำตอบสำหรับคำถามวานิลลา Java ไม่มีเหตุผล
                    Integer.valueOf(String);intไม่ได้ส่งกลับชนิด
                    new Scanner("1244").nextInt()คุณสามารถใช้ หรือถามว่าแม้มี int อยู่:new Scanner("1244").hasNextInt()
ในการเขียนโปรแกรมการแข่งขันที่คุณมั่นใจได้ว่าจำนวนจะเป็นจำนวนเต็มที่ถูกต้องเสมอจากนั้นคุณสามารถเขียนวิธีการของคุณเองเพื่อแยกวิเคราะห์อินพุต การดำเนินการนี้จะข้ามรหัสที่เกี่ยวข้องกับการตรวจสอบความถูกต้องทั้งหมด (เนื่องจากคุณไม่ต้องการรหัสใด ๆ ) และจะมีประสิทธิภาพมากกว่านี้เล็กน้อย
สำหรับจำนวนเต็มบวกที่ถูกต้อง:
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;
}หากคุณต้องการช่องว่างก่อนหรือหลังตัวเลขเหล่านี้ให้ตรวจสอบให้แน่ใจstr = str.trim()ก่อนดำเนินการเพิ่มเติม
เพียงคุณลองทำสิ่งนี้:
Integer.parseInt(your_string);ในการแปลงStringไปintDouble.parseDouble(your_string);ในการแปลงStringไปdoubleString 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
              สำหรับสตริงปกติคุณสามารถใช้:
int number = Integer.parseInt("1234");
สำหรับตัวสร้างสตริงและบัฟเฟอร์สตริงคุณสามารถใช้:
Integer.parseInt(myBuilderOrBuffer.toString());
              int foo=Integer.parseInt("1234");
ตรวจสอบให้แน่ใจว่าไม่มีข้อมูลที่ไม่ใช่ตัวเลขในสตริง
ฉันแปลกใจเล็กน้อยที่ไม่มีใครพูดถึงตัวกำหนดจำนวนเต็มที่ใช้ String เป็นพารามิเตอร์
ดังนั้นนี่คือ:
String myString = "1234";
int i1 = new Integer(myString);
Java 8 - จำนวนเต็ม (String)
แน่นอนคอนสตรัคจะกลับชนิดและการดำเนินการแกะกล่องแปลงค่าเป็นIntegerint
เป็นสิ่งสำคัญที่จะกล่าวถึง : คอนสตรัคนี้เรียกว่าparseIntวิธีการ
public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}
              ใช้ Integer.parseInt () และวางไว้ในtry...catchบล็อกเพื่อจัดการข้อผิดพลาดใด ๆ ในกรณีที่มีการป้อนอักขระที่ไม่ใช่ตัวเลขเช่น
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 str="1234";
int number = Integer.parseInt(str);
print number;//1234
              สามารถทำได้เจ็ดวิธี:
import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;
String number = "999";
1) การใช้Ints.tryParse:
int result = Ints.tryParse(number);
2) การใช้NumberUtils.createInteger:
Integer result = NumberUtils.createInteger(number);
3) การใช้NumberUtils.toInt:
int result = NumberUtils.toInt(number);
4) การใช้Integer.valueOf:
Integer result = Integer.valueOf(number);
5) การใช้Integer.parseInt:
int result = Integer.parseInt(number);
6) การใช้Integer.decode:
int result = Integer.decode(number);
7) การใช้Integer.parseUnsignedInt:
int result = Integer.parseUnsignedInt(number);
              วิธีหนึ่งคือการแยกวิเคราะห์ (สตริง) มันจะส่งกลับดั้งเดิม int:
String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
วิธีที่สองคือ valueOf (String) และส่งคืนออบเจ็กต์ Integer () ใหม่:
String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
              คุณสามารถใช้สิ่งต่อไปนี้:
Integer.parseInt(s)Integer.parseInt(s, radix)Integer.parseInt(s, beginIndex, endIndex, radix)Integer.parseUnsignedInt(s)Integer.parseUnsignedInt(s, radix)Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)Integer.valueOf(s)Integer.valueOf(s, radix)Integer.decode(s)NumberUtils.toInt(s)NumberUtils.toInt(s, defaultValue)นี่เป็นโปรแกรมที่สมบูรณ์ที่มีเงื่อนไขเป็นบวกและลบโดยไม่ต้องใช้ไลบรารี
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;
    }
}
              Integer.parseIntไม่มีความจำเป็นต้องบูรณาการล้อใช้เพียง