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 ofbuffer
(variabletypeCache
) and converts tofloat
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 thefloat
digigtado and converts it (making a cast) ignoring the " n" that in this case is placed inbuffer
also byEnter
– Cold
A solution could put a
nextLine()
to read the supposed " n" that is not considered bynextFloat()
after the end of the internal cycle. It is only a mistrust, so I did not put as an answer. I am still analyzing...– Cold
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.
– urb