我的代码中有一个扫描仪。我希望我的扫描仪只接受字母并在检测到数字时重复用户输入。关于我如何做到这一点的任何想法?
以下是我的示例代码:
if (isFull() == false) {
Scanner input = new Scanner(System.in);
Passenger p = new Passenger();
System.out.print("Enter first name: ");
p.setName(input.nextLine());
System.out.print("Enter surname: ");
p.setSurname(input.nextLine());
queueArray[last] = p;
last = (last + 1) % queueArray.length;
System.out.println("Passenger entered is now in position " + last);
System.out.println("");
}
答案 0 :(得分:0)
您可以使用正则表达式模式来确定用户输入是数字还是字符串:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first name: ");
String a = input.nextLine();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(a);
if(m.matches()){
System.out.println("all characters are digits!");
}
else System.out.println("its a normal string");
}