Results 1 to 2 of 2
- 02-25-2011, 08:04 AM #1
Member
- Join Date
- Feb 2011
- Posts
- 1
- Rep Power
- 0
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, 09:05 AM #2
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
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:
Java 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+" "); } }Ever seen a dog chase its tail? Now that's an infinite loop.
Similar Threads
-
SDF validating date input
By getshum in forum New To JavaReplies: 2Last Post: 02-03-2011, 08:37 AM -
Need help with array and storing input
By Bewitched1 in forum New To JavaReplies: 8Last Post: 07-24-2010, 05:16 PM -
Array Input
By Rose88 in forum New To JavaReplies: 2Last Post: 04-19-2009, 10:39 PM -
input placed in array
By smilejava in forum New To JavaReplies: 5Last Post: 11-12-2007, 07:29 AM -
input placed in array
By smilejava in forum New To JavaReplies: 1Last Post: 11-05-2007, 12:32 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks