Write a for loop to populate array userGuesses with NUM_GUESSES integers. Read integers using Scanner. Ex: If NUM_GUESSES is 3 and user enters 9 5 2, then userGuesses is {9, 5, 2}.
import java.util.Scanner;
public class StoreGuesses { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); final int NUM_GUESSES = 3; int[] userGuesses = new int[NUM_GUESSES]; int i; for (i=0; i < userGuesses ; ++i) { Scanner.nextInt(i); } for (i = 0; i < userGuesses.length; ++i){ System.out.print(userGuesses[i] + " "); } }
}My first loop isn't working.
02 Answers
You are trying to compare an Array with an integer
You are not adding user input in your array This is the for loop you are looking for:
for (i=0; i < NUM_GUESSES ; ++i) { userGuesses[i]=scnr.nextInt(); }
Now in condition we are checking i<NUM_GUESSES , so we will repeat the loop as many times as NUM_GUESSES, and we will be adding each guesss in the array
Okay! So for your first loop, you are asking for the parameters to be from (I = 0; i < userGuesses.length; i++)
for the body of the loop, you need to use the index ("i") to store the values in your array userGuesses[]. When using the Scanner object you need to refer to the object you created not the Scanner class (use your "scnr" not "Scanner")
e.g. userGuesses[i] = scnr.nextInt();