Reputation: 51
In this function, I need a loop that asks the user for 5 numbers between 1 and 10 and stores the numbers in an array call numArray. I need validation on the user's input. I know I need another loop somewhere that will allow the user to enter 5 different numbers, but I don't know where to put it.
public class numberInput {
static int number;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// Calls inputNumbers function
inputNumbers();
}
// inputNumbers function
public static void inputNumbers() {
System.out.println("Please enter 5 numbers between 1 and 10.");
number = keyboard.nextInt();
// If below is true display error message
while (number <= 0 || number > 10) {
System.out.println("Error: Enter a number BETWEEN 1 and 10.");
number = keyboard.nextInt();
}
}
}
Upvotes: 0
Views: 900
Reputation: 620
Just like this, ask for 5 distinct numbers:
public static void inputNumbers() {
ArrayList<Integer> al = new ArrayList<Integer>();
System.out.println("Please enter 5 distinct numbers between 1 and 10.");
for(int i = 0;i<5;i++) {
number = keyboard.nextInt();
// If below is true display error message
while (number <= 0 || number > 10 || al.contains(number)) {//al.contain(number) means does al have number in it
System.out.println("Error: Enter a number BETWEEN 1 and 10.");
number = keyboard.nextInt();
}
al.add(number);//now add the number into the arraylist
}
}
If you want an array, do:
int[] numArray = new int[];
numArray = al.toArray(new int[0]);
Upvotes: 1