Maison  >  Article  >  Java  >  Programme Java pour convertir une chaîne en entier

Programme Java pour convertir une chaîne en entier

WBOY
WBOYavant
2023-08-30 20:41:181161parcourir

Programme Java pour convertir une chaîne en entier

Pour convertir String en int en Java, nous pouvons utiliser deux méthodes intégrées, à savoir parseInt() et valueOf(). Ces méthodes statiques appartiennent à la classe Integer du package java.lang et renvoient une exception NumberFormatException si la chaîne n'est pas une représentation valide d'un entier. En Java, String est une classe du package « java.lang » qui stocke une séquence de caractères entourée de guillemets doubles. De plus, les entiers sont des types de données primitifs qui stockent des valeurs numériques. Dans cet article, nous aborderons certains programmes Java pour illustrer comment convertir une chaîne donnée en entier.

Programme Java pour convertir une chaîne en int

Comme mentionné précédemment, nous convertirons la chaîne en entier en utilisant la méthode suivante -

  • Integer.parseInt()

  • Integer.valueOf()

Discutons de ces méthodes une par une à l'aide d'exemples de programmes.

Utilisez Integer.parseInt()

La méthode

Integer.parseInt() prend une chaîne comme argument et l'analyse en une valeur entière brute.

Grammaire

Integer.parseInt(String val);

Exemple

Le programme Java suivant montre comment convertir String en int à l'aide de la méthode parseInt().

Méthode

  • Initialisez une chaîne qui sera convertie en entier.

  • Ensuite, vérifiez et imprimez le type de la chaîne définie à l'aide des méthodes getClass() et getSimpleName().

  • Maintenant, utilisez la méthode parseInt() pour convertir la chaîne en entier et stocker le résultat dans une variable entière.

  • Enfin, vérifiez et imprimez le type de données pour confirmer si la chaîne est convertie en entier.

public class Example1 {
   public static void main( String args[] ) {
      // initializing a string
      String inputString = "99999";
      // to check the datatype of string 
      System.out.print("Type of inputString: ");
      System.out.println(inputString.getClass().getSimpleName());
      // converting the string into an integer
      int newVal = Integer.parseInt(inputString);
      // printing the result
      System.out.println("The given String after converting into Integer: " + newVal);
      // to check the datatype of integer 
      System.out.print("Type of given String after converting into Integer: ");
      System.out.println(((Object)newVal).getClass().getSimpleName());
   }
}

Sortie

Type of inputString: String
The given String after converting into Integer: 99999
Type of given String after converting into Integer: Integer

Utilisez Integer.valueOf()

La méthode

Integer.valueOf() peut prendre une chaîne, un caractère ou un entier comme paramètre, mais renvoie un objet Integer qui contient la valeur de l'entier analysé.

Grammaire

Integer.valueOf(String val);

Exemple 1

Il s'agit d'un autre programme Java qui montrera comment convertir String en int à l'aide de la méthode Integer.valueOf().

public class Example2 {
   public static void main( String args[] ) {
      // initializing a string
      String inputString = "30072023";
      // to check the datatype of string 
      System.out.print("Type of inputString: ");
      System.out.println(inputString.getClass().getSimpleName());
      // converting the string into an integer
      int newVal = Integer.valueOf(inputString);
      // printing the result
      System.out.println("The given String after converting into Integer: " + newVal);
      // to check the datatype of integer 
      System.out.print("Type of given String after converting into Integer: ");
      System.out.println(((Object)newVal).getClass().getSimpleName());
   }
}

Sortie

Type of inputString: String
The given String after converting into Integer: 30072023
Type of given String after converting into Integer: Integer

Exemple 2

Nous avons mentionné plus tôt que les méthodes parseInt() et valueOf() lanceront une exception NumberFormatException si la chaîne transmise n'est pas une représentation valide d'un entier. Dans ce programme Java, nous passerons une chaîne contenant des caractères alphabétiques au lieu de caractères numériques pour afficher l'exception.

public class Example3 {
   public static void main( String args[] ) {
      // initializing a string
      String inputString = "TutorialsPoint";
      // converting the string to the integer
      int newVal = Integer.valueOf(inputString); // will give exception
      // printing the result
      System.out.println("The given String after converting into Integer: " + newVal);
   }
}

Sortie

Exception in thread "main" java.lang.NumberFormatException: For input string: "TutorialsPoint"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:665)
at java.base/java.lang.Integer.valueOf(Integer.java:992)
at Example3.main(Example3.java:6)

Conclusion

Integer.parseInt() et Integer.valueOf() sont deux méthodes très utiles pour convertir des chaînes en entiers. Cependant, la méthode Integer.valueOf() fonctionne beaucoup plus rapidement que la méthode Integer.parseInt(). Nous discutons de trois programmes Java pour illustrer la mise en œuvre pratique de ces méthodes.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer