Code prints twice but should print only one

0

I would like to know why I run the algorithm on the screen, the line that asks for the student's name to be printed twice.

 Scanner input = new Scanner(System.in);

 System.out.println("Quando o tamanho do conjunto de alunos");
 int tamanho = input.nextInt();

 String[] alunos = new String[tamanho]; 
 for(int i = 0; i < tamanho; i++)
 {
    System.out.println("Digite o nome do aluno");
    alunos[i] = input.nextLine();
 }
    
asked by anonymous 28.09.2014 / 05:00

1 answer

4

If you are answering the first question with 1 , it is because your loop runs once to zero, and once to one. You need to use < instead of <= :

for(int i = 0; i < TAMANHO; i++)

And for each student, instead of picking up what was typed you are picking up the rest of the previous line. Use next() instead of nextLine() :

alunos[i] = input.next();

And why not create a list of the size you need?

String[] alunos = new String[TAMANHO]; 

It would also be recommended not to use TAMANHO so in box-high, it seems like a constant. It would be best to use tamanho .

    
28.09.2014 / 05:21