我试图限制此代码中的用户输入,因此根据选择,允许使用“ D ##”或“ E ##”。我应该如何制定条件?
System.out.println("Please choose one of the following options: ");
System.out.println("1. ");
System.out.println("2. ");
while (!scanner.hasNextInt()) {
System.out.println("You have entered an invalid input. Please choose between options 1 and 2");
scanner.nextLine();
}
choice = scanner.nextInt();
scanner.nextLine();
if (choice == 1) {
System.out.println("Enter an ID of the type D##");
input = scanner.nextLine();
if (input.equals("D" + "[0-9]{2}")) {
System.out.println("Nice");
} else {
System.out.println("Invalid Input");
}
break;
} else if (choice == 2) {
System.out.println("Enter an ID of the type E##");
input = scanner.nextLine();
if (input == "E[0-9]{2}") {
System.out.println("Nice");
} else {
System.out.println("You have entered an invalid input. Please choose between options 1 and 2");
continue;
}
}
答案 0 :(得分:0)
使用java.lang.String.matches代替==
或equals
。
匹配
public boolean matches(String regex)
告诉此字符串是否与给定的正则表达式匹配。 以
完全相同str.matches(regex)
形式调用此方法所产生的结果与表达式Pattern.matches(regex, str)
参数:
regex
-该字符串要匹配的正则表达式返回:
true
仅在此字符串与给定的正则表达式匹配时抛出:
PatternSyntaxException
-如果正则表达式的语法无效因为: 1.4
另请参阅:
Pattern