Results 1 to 2 of 2
  1. #1
    kcoltharp is offline Member
    Join Date
    Feb 2011
    Posts
    1
    Rep Power
    0

    Exclamation 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.

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    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

  1. SDF validating date input
    By getshum in forum New To Java
    Replies: 2
    Last Post: 02-03-2011, 08:37 AM
  2. Need help with array and storing input
    By Bewitched1 in forum New To Java
    Replies: 8
    Last Post: 07-24-2010, 05:16 PM
  3. Array Input
    By Rose88 in forum New To Java
    Replies: 2
    Last Post: 04-19-2009, 10:39 PM
  4. input placed in array
    By smilejava in forum New To Java
    Replies: 5
    Last Post: 11-12-2007, 07:29 AM
  5. input placed in array
    By smilejava in forum New To Java
    Replies: 1
    Last Post: 11-05-2007, 12:32 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •