0

i'm trying to set by user input an array length in java and put inside the array a list of Names. The problem is set when it's start the "for" cycle. It's seems that the programm can't go inside this cycle. I'm posting the code where I have got trouble. Please help me how to solve this problem

 int numPlayer = 0;
 String [] listaNomi = new String []{};
 numPlayer = myInput.nextInt();
  for (int i=0; i<numPlayer; i++)
        {
            byte num=1;
            System.out.println("Inserisci il nome del " +num);
            System.out.print("Giocatore");
            num++;
            Nome = myInput.nextLine();
            Nome = listaNomi[i];
        }

Thanks

  • 1
    There seems to be a bunch of fundamental misunderstandings here, but first and foremost you should be creating the array *after* you take the user input and it should be creating with `numPlayer` as size (`new String[numPlayer];` ) – UnholySheep Sep 06 '20 at 16:34
  • 2
    1) You create the array using `String[] listaNomi = new String[numPlayer];` *after* the `int numPlayer = myInput.nextInt();` statement. --- 2) It's called a "for loop". --- 3) What's the point of `num`? --- 4) See: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045/5221149) --- 5) Last statement needs to assign the other way: `listaNomi[i] = Nome;` – Andreas Sep 06 '20 at 16:37
  • Thanks i listened to your advise and i solved it by declaring the array after the user input, – Stephen Programming Sep 06 '20 at 16:59
  • The problem is now in the "for" loop, on the first access, the "for" loop does not give me the opportunity to type the input. At position 0 in the array it doesn't stop to ask me for input and immediately jumps out and prints the first position in the array, it's like it is skipping a position. – Stephen Programming Sep 07 '20 at 11:49

1 Answers1

1

Try putting "byte num = 1" outside of the for loop. By putting it inside the loop each time the loop runs, the variable is redefined.

TobiSH
  • 2,593
  • 3
  • 18
  • 33
  • Now I tried to put the array declaration after numPlayer, it's solved because, now I can go into the "for" loop, but in the for loop it seems to skip a position, the first time it repeats the loop without stopping for the input. – Stephen Programming Sep 06 '20 at 17:08