Come convertire facilmente una stringa in un numero intero in JAVA

Sommario:

Anonim

Esistono due modi per convertire String in Integer in Java,

  1. Da stringa a numero intero utilizzando Integer.parseInt ()
  2. Da stringa a numero intero utilizzando Integer.valueOf ()

Supponiamo che tu abbia una stringa - strTest - che contiene un valore numerico.
String strTest = “100”;
Prova a eseguire alcune operazioni aritmetiche come dividere per 4: questo mostra immediatamente un errore di compilazione.
class StrConvert{public static void main(String []args){String strTest = "100";System.out.println("Using String: + (strTest/4));}}

Produzione:

/StrConvert.java:4: error: bad operand types for binary operator '/'System.out.println("Using String: + (strTest/4));

Quindi, è necessario convertire una stringa in int prima di eseguire operazioni numeriche su di essa

Esempio 1: convertire una stringa in un numero intero utilizzando Integer.parseInt ()


Sintassi del metodo parseInt come segue:
int  = Integer.parseInt();

Passa la variabile stringa come argomento.
Questo convertirà la stringa Java in java Integer e la memorizzerà nella variabile intera specificata.
Controlla lo snippet di codice seguente-

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

Produzione:

Actual String:100Converted to Int:100Arithmetic Operation on Int: 25

Esempio 2: convertire una stringa in un numero intero utilizzando Integer.valueOf ()

Il metodo Integer.valueOf () viene utilizzato anche per convertire String in Integer in Java.

Di seguito è riportato l'esempio di codice che mostra il processo di utilizzo del metodo Integer.valueOf ():

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

Produzione:

Actual String:100Converted to Int:100Arithmetic Operation on Int:25

NumberFormatException

Viene generata un'eccezione NumberFormatException se si tenta di analizzare una stringa numerica non valida. Ad esempio, la stringa "Guru99" non può essere convertita in numero intero.

Esempio:

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

L'esempio sopra fornisce la seguente eccezione nell'output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Guru99"