# Help with validating input into an array

• 02-25-2011, 09:04 AM
kcoltharp
Help with validating input into an array
I am writing code to get user input, verify input is between 10 and 100, then save int into array.

Everything seems to go ok until a number is less than 10 or more than 100. The original user input number is put into the array.

Is there a way to either rewrite over that index without prior knowledge of the index or prevent it from being input into the array before validating the input.

Here is what I have so far.

int i = 0; //initialize local variable
Scanner input = new Scanner( System.in );
int num[] = new int[10];

for ( int counter = 0; counter < num.length; counter++)
{
System.out.printf("\n\nEnter a number between 10 to 100: ");
num[i] = input.nextInt();
System.out.printf("Counter is at: %d ", counter);

while (num[i] < 10 || num[i] > 100)
{
counter--;
System.out.printf("\nINVALID NUMBER!\n\nEnter a number between "
+ "10 to 100: ");
num[i] = input.nextInt();
}//end while

}//end for loop

Any help would be appreciative.
• 02-25-2011, 10:05 AM
m00nchile
This would be an easier way of doing what you're trying to do, it's simple enough to just write it out, as the program flow of such problems can be a bit hard to understand:
Code:

```public class InputCheckEx {   public static void main(String[] args) {     int[] array = new int[10];     Scanner sc = new Scanner(System.in);     for(int i = 0; i < array.length; i++) {       int input = sc.nextInt();       if(input < 10 || input > 100) {         System.out.println("Input must be between 10 and 100 inclusive.");         i--;       }       else array[i] = input;     }     for(int i: array) System.out.print(i+" ");   } }```