brian.p
brian.p

Reputation: 77

How would I validate User input (names only / no numbers) using an if statement

The following takes in 10 names and then prints them using System.out.println later. I have an if statement below when I enter a number it warns me "do no enter numbers".

The problem is that after the warning prompt I enter 10 names but the number prints off as the first item in the Array? Then the names print afterwards?

import java.io.*;


public class Input {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] myarray = new String[10];


        System.out.println("Enter a 10 names");


        for (int i = 0; i < 10; i++) {


            myarray[i] = br.readLine();
            if (!myarray[i].matches("[a-zA-Z_]+")) {
                System.out.println("Invalid name,please do not enter numbers");
            }
        }
        System.out.println("Here are your names");


        for (int i = 0; i < 10; i++) {

            System.out.println(myarray[i]);

        }
    }
}

Upvotes: 0

Views: 415

Answers (1)

jsheeran
jsheeran

Reputation: 3037

The problem is that when you're rejecting a value you're incrementing the loop counter as if you'd accepted it.

Instead of writing the input to the array, check whether it is valid first:

int i = 0;
while (i < 10) {
  String line = br.readLine();
  if (line.matches("[a-zA-Z_]+") {
    myarray[i++] = line;
  } else {
    System.out.println("Invalid name");
  }
}

Note that i is only incremented when a value is written to the array, and while is used in preference to for since the number of iterations is unknown.

Upvotes: 1

Related Questions