Code prints twice but should print only once

Asked

Viewed 231 times

0

I wonder why at the time I run the algorithm, the line that asks to type the student’s name is printed on the screen 2 times.

 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();
 }
  • 2

    I do not know what was worse, the edition that does not improve the text or the approval of these extremely simplistic editions that do not substantially improve the text, maybe just to gain points.

  • 3

    @moustache the editor is new on the site, and I even understand that he is editing willingly. On the other hand, you can see from the history books that it’s always the same staff who approves editing anyway and doesn’t care about the thing, instead of orienting new users.

  • 1

    @Bacco the intention was to emphasize this very thing :)

1 answer

4

If you are answering the first question with 1, is because your loop rotates once to zero, and again 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’re 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 high-box, it looks like a constant. It would be better to use tamanho.

  • Thanks solved! : D could give me a brief explanation about this nextLine difference to next?

  • 1

    @Ygorramos newtLine moves an internal Scanner cursor to the end of the line, and returns what was before it. next asks for a string and accepts when you enter.

  • 2

    @Ygorramos does not check "solved" on the question, just click the green V on the side of the answer to mark as accepted, the system already treats the question as solved.

Browser other questions tagged

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