Det finns två sätt att konvertera sträng till heltal i Java,
- Sträng till heltal med Integer.parseInt ()
- Sträng till heltal med Integer.valueOf ()

Предложить лучший вариант перевода
String strTest = “100”;Försök att utföra en aritmetisk operation som dividera med 4 - Detta visar dig omedelbart ett kompileringsfel.
class StrConvert{public static void main(String []args){String strTest = "100";System.out.println("Using String: + (strTest/4));}}
Produktion:
/StrConvert.java:4: error: bad operand types for binary operator '/'System.out.println("Using String: + (strTest/4));
Därför måste du konvertera en sträng till int innan du omformar numeriska operationer på den
Exempel 1: Konvertera sträng till heltal med Integer.parseInt ()
Syntax för parseInt-metoden enligt följande:
int= Integer.parseInt( );
Skicka strängvariabeln som argument.
Detta konverterar Java-strängen till Java-heltal och lagrar den i den angivna heltalsvariabeln.
Kontrollera nedanstående kodavsnitt-
class StrConvert{public static void main(String []args){String strTest = "100";int iTest = Integer.parseInt(strTest);System.out.println("Actual String:"+ strTest);System.out.println("Converted to Int: + iTest);//This will now show some arithmetic operationSystem.out.println("Arithmetic Operation on Int: " + (iTest/4));}}
Produktion:
Actual String:100Converted to Int:100Arithmetic Operation on Int: 25
Exempel 2: Konvertera sträng till heltal med Integer.valueOf ()
Metoden Integer.valueOf () används också för att konvertera sträng till heltal i Java.
Följande är kodexemplet visar processen att använda Integer.valueOf () -metoden:
public class StrConvert{public static void main(String []args){String strTest = "100";//Convert the String to Integer using Integer.valueOfint iTest = Integer.valueOf(strTest);System.out.println("Actual String:"+ strTest);System.out.println("Converted to Int: + iTest);//This will now show some arithmetic operationSystem.out.println("Arithmetic Operation on Int: + (iTest/4));}}
Produktion:
Actual String:100Converted to Int:100Arithmetic Operation on Int:25
NumberFormatException
NumberFormatException kastas Om du försöker analysera en ogiltig nummersträng. String 'Guru99' kan till exempel inte konverteras till heltal.
Exempel:
public class StrConvert{public static void main(String []args){String strTest = "Guru99";int iTest = Integer.valueOf(strTest);System.out.println("Actual String:"+ strTest);System.out.println("Converted to Int: + iTest);}}
Ovanstående exempel ger följande undantag i produktionen:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Guru99"