Muzy Muzy - 18 days ago 6
Java Question

String input validation in special form

I'm Trying to except employeenumber XXX-L where x a digit in range 0-9 and L a letter in range of A-M. I'm trying to get this code work. but I can't enter A valid input.

import java.util.Scanner;
import java.util.InputMismatchException;

public class ObjectOrinetPrograming
{
public static void main( String [] args )
{
Scanner input = new Scanner (System.in);
System.out.println("Please Enter elements: ");
String employeenumber = input.nextLine();
while (employeenumber.length() != 5)
{
System.out.println("invalid input; lenght, Try again:");
employeenumber = input.nextLine();
}


while (employeenumber.charAt(4) != ('A'|'B'|'C'|'D'|'E'|'F'|'G'|'H'|'I'|'J'|'K'|'L'|'M'))
{
System.out.print("invalid input; charrecter match, try again:");
employeenumber = input.nextLine();
}


while (employeenumber.charAt(0) == '-')
{
System.out.println("Invalid Input; form, try again:");
employeenumber = input.nextLine();
}
}

}

Answer

You should use matches, which will allow you validate all your inputs:

import java.util.Scanner;
import java.util.InputMismatchException;
public class ObjectOrinetPrograming
{
    public static void main( String [] args )
    {
        Scanner input = new Scanner (System.in);
        System.out.println("Please Enter elements: ");
        String employeenumber = input.nextLine();

        while (!employeenumber.matches("[0-9]{3}-[A-Ma-m]")) {
            System.out.println("invalid input; lenght, Try again:");
            employeenumber = input.nextLine();
        }

    }

}
Comments