特殊形式的字符串输入验证

时间:2016-11-17 00:10:57

标签: java string validation char

我正在尝试除了XXX-L以外的其他x,其中x为0-9范围内的数字,L为A-M范围内的字母。我试图让这段代码工作。但我无法输入有效输入。

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

}

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式来匹配输入java -jar yourJarName.jar

employeenumber

答案 1 :(得分:0)

您应该使用matches,这样您就可以验证所有输入:

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

    }

}