Mike Foski
Mike Foski

Reputation: 29

How do I loop nextInt to define variables in an array?

the question I've asked isn't too clear but essentially I have been tasked to:

Write a program to read in 5 integer numbers from the user. You should store the numbers in an array.

Use loops for efficiency.

I would know how to do this if it weren't for loops, however I am unsure how to use loops for this certain task.

What I have is this (I know this is completely wrong I was just trying to base it on the example from the book).

import java.util.Arrays;
import java.util.Scanner;

public class fivenumbersloops {

public static void main(String[] args)throws Exception {
    Scanner aids = new Scanner(System.in);  
    int[] numbers = new int[5];             
    do
    {
        System.out.println("Enter a whole number: ");
        numbers[0] = aids.nextInt();
        numbers[0]++;
    
    }while (numbers[0]==numbers[5]);
    

    }

}

I know it's the bottom bit which is completely wrong, but if someone could help point me in the right direction I would appreciate it.

Upvotes: 0

Views: 51

Answers (1)

bhspencer
bhspencer

Reputation: 13570

What you want is a for loop. This for loop initializes the variable i to 0, continues while i is less than 5 and increments i for each iteration. The variable i is used to specify the position to place the input number into the array.

public static void main(String[] args) throws Exception {
    Scanner aids = new Scanner(System.in);  
    int[] numbers = new int[5];             
    for (int i = 0; i < 5; i++) {
        System.out.println("Enter a whole number: ");
        numbers[i] = aids.nextInt();
    }
}

Upvotes: 2

Related Questions