Home > Blockchain >  Control of an integer value null
Control of an integer value null

Time:11-14

I'm taking some value with the scanner in class student : mat,name and surname. I want to finish the program when the insert of mat is == "" and not a code. For exemple when i insert mat: 8293 the program go on but when i will insert "" a blank value the program will finish. I think the mat value should be converted to an Integer but don't work the if block.

public static void inserimento() {
    Studente s=null;
    do{
        System.out.println("\nmatricola:");
        Scanner mat = new Scanner(System.in);
        int matricola = mat.nextInt();
        Integer i = Integer.valueOf(matricola);
        if(i.equals(null)){
          break;
        }       
      
        System.out.println("\ncognome:");
        Scanner cog = new Scanner(System.in);
        String cognome = cog.next();
      
        System.out.println("\nnome:");
        Scanner nom = new Scanner(System.in);
        String nome = nom.next();
        s = new Studente(matricola,cognome,nome);
    } while(true);
  
    System.out.println("fine inserimento");
}

CodePudding user response:

You can read the input like string and parse it to an Integer. This allow you to check if the input value is empty.

 public static void inserimento() {

    Studente s=null;
    do{
        System.out.println("\nmatricola:");
        Scanner mat = new Scanner(System.in);
        
        try {
            String matricola = mat.nextLine();
            if(matricola.equals("")){
                break;
            }   
            Integer i = Integer.valueOf(matricola);
            System.out.println("\ncognome:");
            Scanner cog = new Scanner(System.in);
            String cognome = cog.next();
            System.out.println("\nnome:");
            Scanner nom = new Scanner(System.in);
            String nome = nom.next();
            s = new Studente(matricola,cognome,nome);
        }
        catch(Exception e) {
            System.out.println("the input value must be Integer");
        }
       
    } while(true);
    System.out.println("fine inserimento");
}

CodePudding user response:

public static void inserimento() {
Studente s=null;
do{
    System.out.println("\nmatricola:");
    Scanner mat = new Scanner(System.in);
    String matricolaString = mat.nextLine();
    if(!matricolaString.equals(""))
    {
        int i  = Integer.parseInt(matricolaString);
    }
    else{
        break;
    }

    System.out.println("\ncognome:");
    Scanner cog = new Scanner(System.in);
    String cognome = cog.next();
  
    System.out.println("\nnome:");
    Scanner nom = new Scanner(System.in);
    String nome = nom.next();
    s = new Studente(matricola,cognome,nome);
} while(true);

System.out.println("fine inserimento");

}

  • Related