Doubt Scanner class in Java

0

I have this little code. It happens that when the time comes to enter the third data (the name), it jumps, it is as if it were automatically given to enter and could not write anything:

        Scanner sc = new Scanner(System.in);
        System.out.println("Introduce el primer numero: ");
        int num1 = sc.nextInt();
        System.out.println("Introduce el segundo numero: ");
        int num2 = sc.nextInt();
        System.out.println("Introduce tu nombre: ");
        String nombre = sc.nextLine();
        System.out.println("--------------"); //esto no es mas que decoracion

So that the console output would be something like this:

Introduce el primer numero:    
1
Introduce el segundo numero:    
2
Introduce tu nombre:
-------------

I do not know why this happens. It's as if the Scanner class went crazy when I first asked for int and then for String. Do you know what happens?

    
asked by Sergio AG 28.05.2018 в 22:11
source

2 answers

1

This is because the Scanner.nextInt method does not consume the last new line character of its entry and, therefore, that new line is consumed in the next call to Scanner.nextLine .

You will find the same behavior when you use Scanner.nextLine after Scanner.next () or any other method Scanner.nextFoo (except nextLine ).

What you can do is the following:

Scanner sc = new Scanner(System.in);
System.out.println("Introduce el primer numero: ");
int num1 = sc.nextInt();
System.out.println("Introduce el segundo numero: ");
int num2 = sc.nextInt();
//Se consume la siguiente linea
sc.nextLine();
System.out.println("Introduce tu nombre: ");
String nombre = sc.nextLine();
System.out.println("--------------");

Source:

  

link

    
answered by 28.05.2018 / 22:58
source
0

Only change the

String nombre = sc.nextLine();

for

String nombre = sc.next();

For some reason the nextLine () does not let you enter that input.

In case you have doubts about the differences >

next () reads until it finds a space (stops reading in the first space)

nextLine () reads the entire line (stops reading in the line break)

    
answered by 28.05.2018 в 22:50