gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:02:35 25 4
gpt4 key购买 nike

我正在尝试排除员工编号 XXX-L,其中 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();
}
}

}

最佳答案

您可以使用正则表达式来匹配输入的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);

}

关于java - 特殊形式的字符串输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com