Controlla se una stringa è un numero intero in Java
- 
          
            Controlla se la stringa è un numero intero da Character.digit()in Java
- 
          
            Controlla se la stringa è un numero intero da string.matches(pattern)in Java
- 
          
            Controlla se la stringa è un numero intero da Scanner.nextInt(radix)in Java
 
Le stringhe e i numeri interi in Java vengono spesso utilizzati per la memorizzazione dei dati, ma a volte potremmo voler verificare se un tipo di dati contiene elementi compatibili con un altro tipo di dati o meno.
Poiché sappiamo che una stringa può contenere alfabeti, simboli e numeri, è utile per determinare il tipo di dati che contiene la nostra stringa. Vedremo esempi di controllo della stringa con metodi diversi.
Controlla se la stringa è un numero intero da Character.digit() in Java
Possiamo vedere che il seguente esempio ha tre stringhe che possiamo passare alla funzione isStringInteger(stringToCheck, radix). radix dice l’intervallo del numero che vogliamo ottenere, qui stiamo usando 10, che consente l’intervallo da 0 a 9.
Character.digit() controlla ogni carattere nella stringa e restituisce un numero maggiore di 0 se è una cifra. È inoltre possibile aggiungere istruzioni condizionali aggiuntive per rendere il risultato accurato.
public class Main {
  public static void main(String[] args) {
    String str1 = "ABC123";
    String str2 = "3030";
    String str3 = "-9";
    boolean integerOrNot1 = isStringInteger(str1, 10);
    System.out.println("Is " + str1 + " an Integer? -> " + integerOrNot1);
    boolean integerOrNot2 = isStringInteger(str2, 10);
    System.out.println("Is " + str2 + " an Integer? -> " + integerOrNot2);
    boolean integerOrNot3 = isStringInteger(str3, 10);
    System.out.println("Is " + str3 + " an Integer? -> " + integerOrNot3);
  }
  public static boolean isStringInteger(String stringToCheck, int radix) {
    if (stringToCheck.isEmpty())
      return false; // Check if the string is empty
    for (int i = 0; i < stringToCheck.length(); i++) {
      if (i == 0 && stringToCheck.charAt(i) == '-') { // Check for negative Integers
        if (stringToCheck.length() == 1)
          return false;
        else
          continue;
      }
      if (Character.digit(stringToCheck.charAt(i), radix) < 0)
        return false;
    }
    return true;
  }
}
Produzione:
Is 12000003 an Integer? -> true
Controlla se la stringa è un numero intero da string.matches(pattern) in Java
Nel prossimo metodo per identificare se la stringa contiene elementi Integer, possiamo usare l’espressione regolare, che può aiutare a trovare un modello specifico, cioè un valore numerico. -?\\d+ è l’espressione che possiamo confrontare con la stringa e ottenere il risultato in un tipo booleano.
public class Main {
  public static void main(String[] args) {
    String str1 = "ABC123";
    String str2 = "123";
    String str3 = "000000009";
    boolean integerOrNot1 = str1.matches("-?\\d+");
    System.out.println("Is " + str1 + " an Integer? -> " + integerOrNot1);
    boolean integerOrNot2 = str2.matches("-?\\d+");
    System.out.println("Is " + str2 + " an Integer? -> " + integerOrNot2);
    boolean integerOrNot3 = str3.matches("-?\\d+");
    ;
    System.out.println("Is " + str3 + " an Integer? -> " + integerOrNot3);
  }
}
Produzione:
Is ABC123 an Integer? -> false
Is 123 an Integer? -> true
Is 000000009 an Integer? -> true
Controlla se la stringa è un numero intero da Scanner.nextInt(radix) in Java
Possiamo anche usare la famosa classe Scanner() di Java. Il suo metodo nextInt() può controllare se la stringa data è di tipo Int oppure no.
import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    String str1 = "ABC123";
    String str2 = "3030";
    String str3 = "000000009";
    System.out.println("Is " + str1 + " an Integer? -> " + isStringInteger(str1, 10));
    System.out.println("Is " + str2 + " an Integer? -> " + isStringInteger(str2, 10));
    System.out.println("Is " + str3 + " an Integer? -> " + isStringInteger(str3, 10));
  }
  public static boolean isStringInteger(String stringToCheck, int radix) {
    Scanner sc = new Scanner(stringToCheck.trim());
    if (!sc.hasNextInt(radix))
      return false;
    sc.nextInt(radix);
    return !sc.hasNext();
  }
}
Produzione:
Is ABC123 an Integer? -> false
Is 3030 an Integer? -> true
Is 000000009 an Integer? -> true
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedInArticolo correlato - Java String
- Converti array di byte in stringa esadecimale in Java
- Converti stringa Java in byte
- Eseguire la conversione di array da stringa a stringa in Java
- Rimuovi sottostringa dalla stringa in Java
- Confronta le stringhe in Java
- Genera stringa casuale in Java
