Problem reading strings and numbers in sequence with Scanner

Asked

Viewed 85 times

0

I came across this problem in the code at the time the program will read the second name and the second name note, ie the name of the second student and his grade. Can you explain to me what happened ?

Scanner teclado = new Scanner (System.in);

String []nome = new String [5];
int []notas = new int [5];

for (int i = 0; i < 5; i++) {
     System.out.println("Nome " + (i+1));
     nome[i] = teclado.nextLine();
     
     System.out.println("Nota " + (i+1));
     notas[i] = teclado.nextInt();
}

1 answer

1

The problem happens because of that here.

Basically, nextInt only reads the minimum required to have an integer number. So it does not consume line break (the ENTER that the user types), and this is consumed by the next call of nextLine (that is, the second name will be an empty string, since it only has the line break to be read and will be interpreted as an empty line).

The solution is to use nextLine in both cases, and then convert the String for int:

for (int i = 0; i < 5; i++) {
    System.out.println("Nome " + (i + 1));
    nome[i] = teclado.nextLine();

    System.out.println("Nota " + (i + 1));
    notas[i] = Integer.parseInt(teclado.nextLine());
}

Another option is to call nextLine then to force the reading of the break line, so it does not interfere with the next reading of the name:

for (int i = 0; i < 5; i++) {
    System.out.println("Nome " + (i + 1));
    nome[i] = teclado.nextLine();

    System.out.println("Nota " + (i + 1));
    notas[i] = teclado.nextInt();
    teclado.nextLine(); // <-- aqui
}

It is worth noting that both your code and mine above will fail if a number is not entered. If you want to validate, just make a loop that keeps asking you to type again while it’s not a number:

for (int i = 0; i < 5; i++) {
    System.out.println("Nome " + (i + 1));
    nome[i] = teclado.nextLine();

    while (true) {
        try {
            System.out.println("Nota " + (i + 1));
            notas[i] = Integer.parseInt(teclado.nextLine());
            break; // se chegou aqui, é número, interrompe o while
        } catch (NumberFormatException e) {
            System.out.println("Não foi digitado um número");
        }
    }
}

The same problem occurs if other methods that do not consume line breaking are used, such as nextDouble, nextLong, nextFloat, etc..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.