Java Class Scanner Loop Error

Asked

Viewed 1,206 times

6

When using the nextLine() method instead of next() in the code below, code interactions are skipped and some fields are empty.

import java.util.Scanner;
public class turma {

    public static void main (String args[]) {
        final byte tamanho=10;
        byte k=tamanho;
        Scanner entrada=new Scanner(System.in);
        float notas[][]=new float[tamanho][3];// A matriz possui 10 linhas e três colunas(uma para cada prova e a última para a média);
        String nomes[][]=new String[tamanho][2];//A matriz possui 10 linhas (alunos) e duas colunas, uma para o nome e a outra para a situação
        System.out.println("Cadastro de Turma:");
        for (byte i=0; i<=(k-1); i++) { //laço para as linhas
                System.out.println("Entre com o nome do "+(i+1)+"º aluno:");
                //entrada.nextLine();
                nomes[i][0]=entrada.nextLine();

                for (byte y=0;y<=1;y++){
                    System.out.println("Entre com a "+(y+1)+"ª nota:");
                    notas[i][y]=entrada.nextFloat();
                }//fim do for interno
                notas[i][2]=(notas[i][0]+notas[i][1])/2;
                if (notas[i][2]>=7) nomes[i][1]="Aprovado"; else nomes[i][1]="Repovado";
        }//for externo
        System.out.println("Relatório de Notas");
        System.out.println("\nNome \t\tNota 1 \t\tNota 2 \t\tMédia \t\tSituação");
        for (byte i=0; i<=(k-1);i++) System.out.println(nomes[i][0]+"\t\t"+notas[i][0]+"\t\t"+notas[i][1]+"\t\t"+notas[i][2]+"\t\t"+nomes[i][1]);

    }//fim do main
}//fim da classe
  • That’s good :D. I’m here trying to see what’s really going on and when it comes time to read the second or nth name (n != 1) it considers empty. I took a look at the implementation of nextFloat() and I observed that he reads the next element of buffer (variable typeCache) and converts to float and then it returns (if it is an invalid value it gives an exception, and I recommend you pay attention to it). My mistrust is that it reads only the value in question, in this case the float digigtado and converts it (making a cast) ignoring the " n" that in this case is placed in buffer also by Enter

  • A solution could put a nextLine() to read the supposed " n" that is not considered by nextFloat() after the end of the internal cycle. It is only a mistrust, so I did not put as an answer. I am still analyzing...

  • You should also pay attention to clear the input buffer. The input buffer is basically what the user writes, if there is garbage there the code understands that it was the user and will never stop for the user to write.

4 answers

3


1st Mode:

nomes[i][0]=lerString();
for (int y=0;y<=1;y++){
     System.out.println("Entre com a "+(y+1)+"ª nota:");
     notas[i][y]=entrada.nextFloat();
}//fim do for interno

//[...]

public static String lerString(){
     return entrada.next()+entrada.nextLine();
}

Don’t forget to declare the scanner entrada as static to be recognised in the.

2º Modo(recommended)

   nomes[i][0]=entrada.nextLine();
    for (int y=0;y<=1;y++){
         System.out.println("Entre com a "+(y+1)+"ª nota:");
         notas[i][y]=entrada.nextFloat();
    }//fim do for interno
    entrada.nextLine()//descarrega o buffer do teclado, antes de ler a próxima string

whenever reading a string after reading a numeric value you need to download the keyboard buffer before reading the string,.

0

The right thing would be for you to use a different scanner for each primitive variable type. Or clean the contents inside your Scanner and use it again (I don’t recommend)

0

Here’s a Gambi to solve your problem.

Change this:

nomes[i][0]=entrada.nextLine();

That’s why:

String lido = null;
do {
    lido = entrada.nextLine();
} while (lido == null || lido.trim().isEmpty());
nomes[i][0]=lido;

-4

Put the Scanner entrada=new Scanner(System.in); after the loop that works.

Browser other questions tagged

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