Java >> Tutoriel Java >  >> Tag >> String

Comment vérifier si la chaîne est un nombre en Java?

Nous vérifierons si la chaîne est un nombre ou non - avec l'aide de la logique, nous résoudrons ce problème,

  • Dans la première étape, nous prendrons une variable de chaîne nommée str et y stockerons n'importe quelle valeur.
  • Dans la deuxième étape, nous prendrons une variable booléenne nommée str_numeric qui stocke la valeur booléenne comme true ou false. Supposons que la chaîne donnée soit numérique afin que la variable booléenne initiale str_numeric soit définie sur true.
  • Dans la troisième étape, nous ferons une chose dans le bloc try, nous convertirons la variable String en Double en utilisant la méthode parseDouble() car initialement nous supposons que la chaîne étant un nombre, c'est pourquoi nous convertissons en premier.
  • >
  • S'il génère une erreur (c'est-à-dire NumberFormatException), cela signifie que la chaîne donnée n'est pas un nombre et qu'en même temps, la variable booléenne str_numeric est définie sur false. Sinon, la chaîne donnée est un nombre.

Exemple :

public class IsStringNumeric {
    public static void main(String[] args) {
        // We have initialized a string variable with double values
        String str1 = "1248.258";
        // We have initialized a Boolean variable and 
        // initially we are assuming that string is a number 
        // so that the value is set to true        
        boolean str_numeric = true;

        try {
            // Here we are converting string to double 
            // and why we are taking double because 
            // it is a large data type in numbers and 
            // if we take integer then we can't work 
            // with double values because we can't covert 
            // double to int then, in that case, 
            // we will get an exception so that Boolean variable 
            // is set to false that means we will get wrong results. 
            Double num1 = Double.parseDouble(str1);
        }

        // Here it will raise an exception 
        // when given input string is not a number 
        // then the Boolean variable is set to false. 
        catch (NumberFormatException e) {
            str_numeric = false;
        }

        // if will execute when given string is a number
        if (str_numeric)
            System.out.println(str1 + " is a number");
        // Else will execute when given string is not a number       
        else
            System.out.println(str1 + " is not a number");
    }
}

Sortie

D:\Programs>javac IsStringNumeric.java

D:\Programs>java IsStringNumeric
1248.258 is a number

Balise Java