Jak przekonwertować ciąg znaków na int w Javie?

Jak mogę przekonwertować String na int w Javie?

Mój łańcuch zawiera tylko liczby i chcę zwrócić liczbę, którą reprezentuje.

Na przykład, biorąc pod uwagę łańcuch "1234" wynikiem powinna być Liczba 1234.

Author: Peter Mortensen, 2011-04-07

30 answers

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

Zobacz Dokumentacja Java aby uzyskać więcej informacji.

 3629
Author: Rob Hruska,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-10 09:27:34

Na przykład, oto dwa sposoby:

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

Istnieje niewielka różnica między tymi metodami:

  • valueOf zwraca nową lub buforowaną instancję java.lang.Integer
  • parseInt zwraca primitive int.

To samo dotyczy wszystkich przypadków: Short.valueOf/parseShort, Long.valueOf/parseLong, itd.

 606
Author: smas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-30 20:15:43

Bardzo ważną kwestią do rozważenia jest to, że parser liczb całkowitych wyrzuca wartość NumberFormatException, jak podano w 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.
}

Ważne jest, aby obsłużyć ten wyjątek podczas próby uzyskania wartości całkowitych z podzielonych argumentów lub dynamicznego parsowania czegoś.

 221
Author: Ali Akdurak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-16 23:35:36

Zrób to ręcznie:

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;
}
 75
Author: Billz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-30 14:31:00

Obecnie robię zadanie na studia, gdzie nie mogę używać pewnych wyrażeń, takich jak te powyżej, i patrząc na tabelę ASCII, udało mi się to zrobić. To znacznie bardziej złożony kod, ale może pomóc innym, którzy są ograniczeni, tak jak ja.

Pierwszą rzeczą do zrobienia jest odebranie wejścia, w tym przypadku, ciągu cyfr; nazwę go String number, a w tym przypadku, będę go zilustrować używając liczby 12, zatem String number = "12";

Innym ograniczeniem był fakt, że ja nie można używać powtarzalnych cykli, dlatego też nie można używać cyklu for (który byłby idealny). To nas trochę ogranicza, ale z drugiej strony, taki jest cel. Ponieważ potrzebowałem tylko dwóch cyfr( biorąc dwie ostatnie cyfry), proste charAt rozwiązało to:

 // 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);
Mając kody, wystarczy spojrzeć na tabelę i dokonać niezbędnych korekt:]}
 double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;
Dlaczego podwójnie? Cóż, z powodu naprawdę "dziwnego" kroku. Obecnie mamy dwa sobowtóry, 1 i 2, ale musimy zamienimy to na 12, nie ma żadnej matematycznej operacji, którą możemy wykonać.

Dzielimy to drugie (lastdigit) przez 10 w sposób 2/10 = 0.2 (stąd dlaczego podwójne) w ten sposób:

 lastdigit = lastdigit/10;

To tylko gra liczbami. Zmienialiśmy ostatnią cyfrę na dziesiętną. Ale teraz zobacz co się dzieje:

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

Nie wdając się zbytnio w matematykę, po prostu izolujemy jednostki cyfr liczby. Widzisz, ponieważ rozważamy tylko 0-9, dzielenie przez wielokrotność 10 jest jak tworzenie "pudełka", w którym go przechowujesz (przypomnij sobie, kiedy nauczyciel pierwszej klasy wyjaśnił ci, czym była jednostka i sto). Więc:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"
No i proszę. W tym przypadku dwie cyfry zostały zamienione na liczbę całkowitą składającą się z tych dwóch cyfr, biorąc pod uwagę następujące ograniczenia:
  • brak powtarzających się cykli
  • brak "magicznych" wyrażeń, takich jak parseInt
 40
Author: Oak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-25 20:08:55

Alternatywnym rozwiązaniem jest użycie Apache Commons ' NumberUtils:

int num = NumberUtils.toInt("1234");

Narzędzie Apache jest ładne, ponieważ jeśli łańcuch znaków jest nieprawidłowym formatem liczb, to zawsze zwracane jest 0. Dzięki temu oszczędzasz blok połowu próbnego.

Apache NumberUtils API Wersja 3.4

 36
Author: Ryboflavin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-05 22:25:28

Integer.decode

Możesz również użyć public static Integer decode(String nm) throws NumberFormatException.

Działa również dla bazy 8 i 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

Jeśli Chcesz otrzymać int zamiast Integer możesz użyć:

  1. Unboxing:

    int val = Integer.decode("12"); 
    
  2. intValue():

    Integer.decode("12").intValue();
    
 29
Author: ROMANIA_engineer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-07 00:42:49

Gdy istnieje najmniejsza możliwość, że dany łańcuch nie zawiera liczby całkowitej, musisz obsłużyć ten specjalny przypadek. Niestety, standardowe metody Javy Integer::parseInt i Integer::valueOf rzucają NumberFormatException, aby zasygnalizować ten szczególny przypadek. Dlatego musisz użyć wyjątków dla kontroli przepływu, co jest ogólnie uważane za zły styl kodowania.

Moim zdaniem, ta szczególna sprawa powinna być załatwiona przez zwrócenie Optional<Integer>. Ponieważ Java Nie oferuje takiej metody, używam następujących "wrapper": {]}

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

Użycie:

// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));

Podczas gdy nadal używa się WYJĄTKÓW do wewnętrznej kontroli przepływu, kod użycia staje się bardzo czysty.

 23
Author: Stefan Dollase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-04 03:20:37

Konwersja ciągu znaków na int jest bardziej skomplikowana niż konwersja liczby. Zastanów się nad następującymi kwestiami:

  • czy łańcuch zawiera tylko liczby 0-9?
  • What ' s up with -/+ przed czy po sznurku? Czy jest to możliwe (odnosząc się do numerów księgowych)?
  • o co chodzi z MAX_ - / MIN_INFINITY? co się stanie, jeśli ciąg znaków będzie wynosił 999999999999999999999? Czy maszyna może traktować ten ciąg jako int?
 21
Author: Dennis Ahaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 02:31:44

Możemy użyć metody parseInt(String str) klasy opakowującej Integer do konwersji wartości ciągu znaków na wartość całkowitą.

Na przykład:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

Klasa Integer zapewnia również metodę valueOf(String str):

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

Możemy również użyć toInt(String strValue)z klasy użytkowej Numeratils do konwersji:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
 20
Author: Giridhar Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-16 23:50:47

Użycie Integer.parseInt(yourString)

Pamiętaj o następujących rzeczach:

Integer.parseInt("1"); // ok

Integer.parseInt("-1"); // ok

Integer.parseInt("+1"); // ok

Integer.parseInt(" 1"); // Exception (blank space)

Integer.parseInt("2147483648"); // wyjątek (liczba całkowita jest ograniczona do maksymalnej wartości 2,147,483,647)

Integer.parseInt("1.1"); // Exception (. lub , lub cokolwiek jest niedozwolone)

Integer.parseInt(""); // Exception (not 0 or something)

Istnieje tylko jeden rodzaj wyjątek: NumberFormatException

 18
Author: Lukas Bauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-06 19:55:17

Mam rozwiązanie, ale nie wiem, jak skuteczne. Ale to działa dobrze, i myślę, że można to poprawić. Z drugiej strony, zrobiłem kilka testów z JUnit który krok poprawnie. Załączyłem funkcję i testowanie:

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

Testowanie z 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));
        }
    }
}
 17
Author: fitorec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-29 08:36:51

Metody do tego:

 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)

Liczba całkowita.valueOf produkuje obiekt Integer, wszystkie inne metody-primitive int.

Ostatnie 2 metody z commons-lang3 i duży artykuł o konwersji tutaj .

 17
Author: Dmytro Shvechikov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-09 19:45:55

Dla zabawy: możesz użyć Javy 8 Optional do konwersji String na 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.

Tutaj po prostu łączymy Integer.valueOf i Optinal. Prawdopodobnie mogą się zdarzyć sytuacje, w których jest to przydatne - na przykład, gdy chcesz uniknąć sprawdzania null. Kod Pre Java 8 będzie wyglądał tak:

Integer value = (str == null) ? -1 : Integer.parseInt(str);
 16
Author: Anton Balaniuc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-25 20:13:19

Guava ma tryParse (String) , które zwraca null jeśli łańcuch nie może być przetworzony, na przykład:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}
 14
Author: Vitalii Fedorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-06 17:56:29

Możesz również rozpocząć od usunięcia wszystkich znaków nie-numerycznych, a następnie przetworzyć int:

string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);

Ale ostrzegam, że działa to tylko dla liczb nieujemnych.

 12
Author: Thijser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-25 19:48:23

Oprócz powyższych odpowiedzi, chciałbym dodać kilka funkcji:

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

A oto wyniki podczas ich uruchamiania:

  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
  }
 10
Author: nxhoaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-12 14:27:11

Możesz użyć new Scanner("1244").nextInt(). Lub zapytać, czy nawet int istnieje: new Scanner("1244").hasNextInt()

 9
Author: Christian Ullenboom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-28 20:36:40

Możesz również użyć tego kodu, zachowując pewne środki ostrożności.

  • Opcja #1: obsłuż wyjątek jawnie, na przykład wyświetlając okno dialogowe wiadomości, a następnie zatrzymaj wykonywanie bieżącego obiegu pracy. Na przykład:

    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;
    }
    
  • Opcja #2: Zresetuj zmienną, której to dotyczy, jeśli przepływ wykonania może być kontynuowany w przypadku wyjątku. Na przykład, z pewnymi modyfikacjami w bloku catch

    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

Używanie stałej łańcuchowej dla porównania lub dowolnego rodzaju obliczanie jest zawsze dobrym pomysłem, ponieważ stała nigdy nie zwraca wartości null.

 8
Author: manikant gautam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-05 04:28:17

Jak wspomniano Apache Commons NumberUtils może to zrobić. Które zwracają 0, Jeśli nie można przekonwertować ciągu znaków na int.

Można również zdefiniować własną wartość domyślną.

NumberUtils.toInt(String str, int defaultValue)

Przykład:

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; 
 8
Author: Alireza Fattahi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-26 05:41:55

W konkursach programistycznych, gdzie masz pewność, że liczba zawsze będzie poprawną liczbą całkowitą, możesz napisać własną metodę do analizy danych wejściowych. Spowoduje to pominięcie całego kodu związanego z walidacją (ponieważ nie potrzebujesz żadnego z nich) i będzie nieco bardziej wydajne.

  1. Dla poprawnej dodatniej liczby całkowitej:

    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;
    }
    
  2. Zarówno dla dodatnich, jak i ujemnych liczb całkowitych:

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

     

  3. Jeśli spodziewasz się białej spacji przed lub po tych liczbach, wtedy przed dalszym przetwarzaniem upewnij się, że wykonasz str = str.trim().

 8
Author: Raman Sahasi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-24 05:36:19

Po prostu możesz spróbować tego:

  • Użyj Integer.parseInt(your_string);, aby przekształcić String na int
  • Użyj Double.parseDouble(your_string);, aby przekształcić String na double

Przykład

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
 7
Author: Vishal Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-21 12:12:17

Dla zwykłego ciągu można użyć:

int number = Integer.parseInt("1234");

Dla String builder i String buffer można użyć:

Integer.parseInt(myBuilderOrBuffer.toString());
 6
Author: Aditya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-18 07:07:24
int foo=Integer.parseInt("1234");

Upewnij się, że w łańcuchu nie ma danych innych niż numeryczne.

 6
Author: iKing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-08 22:24:54

Here we go

String str="1234";
int number = Integer.parseInt(str);
print number;//1234
 6
Author: Shivanandam Sirmarigari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-09 15:05:12

Jestem trochę zaskoczony, że nikt nie wspomniał o konstruktorze Integer, który przyjmuje String jako parametr.
Oto:

String myString = "1234";
int i1 = new Integer(myString);

Java 8-Integer (String) .

Oczywiście konstruktor zwróci typ Integer, a operacja unboxingu zamieni wartość na int.


Ważne jest, aby wspomnieć
Ten konstruktor wywołuje metodę parseInt.

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}
 6
Author: djm.im,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-09 14:56:52

Jedną z metod jest parseInt (String) zwraca prymitywną int

String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);

Druga metoda to valueOf (String) zwraca nowy obiekt Integer ().

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
 5
Author: Pankaj Mandale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-12 14:25:51

Użyj Liczby Całkowitej.parseInt() i umieść go wewnątrz bloku try...catch, Aby obsłużyć wszelkie błędy tylko w przypadku wprowadzenia znaku nieliczbowego, na przykład

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);
    }
 }
 5
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-21 22:33:28

Jest to kompletny program ze wszystkimi warunkami dodatnimi, ujemnymi bez użycia biblioteki

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;
     }
    }
 4
Author: Anup Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-01 06:53:39

Przy okazji, należy pamiętać, że jeśli łańcuch jest null, wywołanie:

int i = Integer.parseInt(null);

Rzuca NumberFormatException, nie NullPointerException.

 3
Author: Pavel Molchanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 21:26:24