Muzy
Muzy

Reputation: 15

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();
        }
        }

}

Upvotes: 1

Views: 68

Answers (2)

Raghav
Raghav

Reputation: 4638

You can use regular expression to match input employeenumber.

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-M]")) {
        System.out.println("invalid input; lenght, Try again:");
        employeenumber = input.nextLine();
    }

    System.out.println("Your employee id is " + employeenumber);

}

Upvotes: 1

BlackHatSamurai
BlackHatSamurai

Reputation: 23493

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();
        }

    }

}

Upvotes: 0

Related Questions