Java - Convertir un String en int
En Java, pour convertir un String en int, vous pouvez utiliser Integer.parseInt() ou Integer.valueOf().
En cas ou le string n'est pas accepté parce qu'il contient un caractère alphabétique par exemple, une NumberFormatException va être déclenchée.
Ressources:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(java.lang.String, int)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
Exemple de Integer.parseInt()
String nombre_str = "22";Exécution:
int nombre = Integer.parseInt(nombre_str);
System.out.println(nombre);
22
Exemple de Integer.valueOf()
La méthode Integer.valueOf() va retourner un objet Integer.String nombre_s = "22";Exécution
int nombre = Integer.valueOf(nombre_s);
System.out.println(nombre);
22
En cas ou le string n'est pas accepté parce qu'il contient un caractère alphabétique par exemple, une NumberFormatException va être déclenchée.
String nombre_s = "9Ab";En sortie:
int nombre = Integer.parseInt(nombre_s);
System.out.println(nombre);
Exception in thread "main" java.lang.NumberFormatException: For input string: "9Ab"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
Ressources:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(java.lang.String, int)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)