Possible restriction in Eclipse? with Java [duplicated]

1

I have in my code several System.out.println () asking certain things and picking up in their corresponding variable what the user enters through the keyboard. The fact is that after several System.out.println (), Eclipse is as if you ignored the last one and will not let you enter anything by keyboard because it has advanced with the program. I have checked the code again and again for errors but nothing. Could it be a limitation of Eclipse? What do you think?

Thank you very much and greetings.

PS: the piece of code is inside main

        Scanner sc = new Scanner(System.in);

        String DNI = null;


        while((DNI == null) || (DNI.equals("")) || DNI.length()<6){

            System.out.println("El DNI es obligatorio para la creacion "
                            + "de un alumno.");

            System.out.println("Introduce el DNI: ");
            DNI = sc.nextLine();

            if(DNI!=null && DNI.length()<6){
                System.out.println("El DNI introducido es demasiado corto.");
                    }
                }


        System.out.println("Introduce la direccion: ");
        String direccion = sc.nextLine();

        System.out.println("Introduce el nombre: ");
        String nombre = sc.nextLine();

        System.out.println("Introduce tu fecha de nacimiento "
                + "(AAAA-MM-DD): ");
        String edad = sc.nextLine();

        System.out.println("Introduce el telefono: ");
        int telefono = sc.nextInt();

        System.out.println("Introduce el cif de empresa: ");
        String CIFEmpresa = sc.nextLine();
    
asked by 03.09.2017 в 02:56
source

1 answer

1

Problem

The problem is in sc.nextInt() . This function will only read an integer, but since you have pressed Enter to send it, you have also sent a \n so your next call to nextLine() will read that \n .

Example of the problem

I put you in situation. Suppose I do the following:

System.out.println("Introduce el nombre: ");
nextLine();
System.out.println("Introduce la edad: ");
nextInt();
System.out.println("Introduce el apellido: ");
nextLine();
System.out.println("Fin.");

To fill in that data, I would send the following inputs (the \n are not visible, but I'll put them for you to see):

Introduce el nombre: 
DanielGS\n
Introduce la edad:
23\n
Introduce el apellido:
Fin.

What happened there? Well, the nextLine () to get the last name has taken the \n of the age, since nextInt () only takes the whole.

How to fix it?

Simply adding a nextLine () to take that \n that stays around.

System.out.println("Introduce el nombre: ");
nextLine();
System.out.println("Introduce la edad: ");
nextInt();
nextLine();
System.out.println("Introduce el apellido: ");
nextLine();
System.out.println("Fin.");
  

Another option could be to read the age with a nextLine () and then do a full conversion.

    
answered by 03.09.2017 в 11:43