Luis Torres
Luis Torres

Reputation: 49

I can't add numbers to an array with the for loop and scanner

Here is my code:

import java.util.Scanner;


public class Test2 {
    public static void main(String[] args){
        final int NUMBER_AMOUNT = 6;
        int playerNums[] = new int[NUMBER_AMOUNT];
        Scanner keyboard = new Scanner(System.in);

        int index = 0;

        for(int i = 1; i < playerNums.length; i++)
            index = i;
            System.out.println("Please enter " + NUMBER_AMOUNT + " numbers");
            playerNums[index] = keyboard.nextInt();

        keyboard.close();

    }

}

For some reason it doesn't allow me to enter the number 6 times. It just lets me do it once and then stops the program. Can anyone tell me why?

Upvotes: 0

Views: 49

Answers (3)

S.Yavari
S.Yavari

Reputation: 876

Simply change the for loop as follow

for(int i = 1; i <= playerNums.length; i++) {
        System.out.println("Please enter " + NUMBER_AMOUNT + " numbers");
        playerNums[i-1] = keyboard.nextInt();
}

Note that you have to pay attention to <= and start/end brackets.

Upvotes: 0

AnkeyNigam
AnkeyNigam

Reputation: 2820

You need to add the statements to be executed under for loop in between { and } . So you need to use the braces{} in for loop like :-

for(int i = 1; i < playerNums.length; i++){ // loop start
            index = i;
            System.out.println("Please enter " + NUMBER_AMOUNT + " numbers");
            playerNums[index] = keyboard.nextInt();
     } //loops ends

Everything else looks totally fine .

Upvotes: 0

singhakash
singhakash

Reputation: 7919

Put you statements inside loop by adding curly braces {} to mention the scope of loop.

  for(int i = 1; i < playerNums.length; i++){
            index = i;
            System.out.println("Please enter " + NUMBER_AMOUNT + " numbers");
            playerNums[index] = keyboard.nextInt();
  }

With your code only one line after the for loop is considered as a part of the loop and executed on loop iterations.

Upvotes: 3

Related Questions