简体   繁体   中英

Control of an integer value null

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");
}

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 an Integer");
        }
       
    } while(true);
    System.out.println("fine inserimento");
}
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");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM