python限制user输入字母,将用户的字符串输入限制为字母和数字值

Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.

my current code:

switch (studentMenu) {

case 1: // Change all four fields

System.out.println("Please enter in a first name: ");

String firstNameIntermediate = scan.next();

firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);

System.out.println("Please enter in a middle name");

middleName = scan.next();

System.out.println("Please enter in a last name");

lastName = scan.next();

System.out.println("Please enter in an eight digit student ID number");

changeID();

break;

case 2: // Change first name

System.out.println("Please enter in a first name: ");

firstName = scan.next();

break;

case 3: // Change middle name

System.out.println("Please enter in a middle name");

middleName = scan.next();

break;

case 4: // Change last name

System.out.println("Please enter in a last name");

lastName = scan.next();

case 5: // Change student ID:

changeID();

break;

case 6: // Exit to main menu

menuExit = true;

default:

System.out.println("Please enter a number from 1 to 6");

break;

}

}

}

public void changeID() {

studentID = scan.next();

}

I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.

解决方案

java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX methods.

Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+:

Scanner sc = new Scanner(System.in);

System.out.println("Please enter letters:");

while (!sc.hasNext("[A-Za-z]+")) {

System.out.println("Nope, that's not it!");

sc.next();

}

String word = sc.next();

System.out.println("Thank you! Got " + word);

Here's an example session:

Please enter letters:

@#$

Nope, that's not it!

123

Nope, that's not it!

james bond

Thank you! Got james

To validate that the next token is a number that you can convert to int, use hasNextInt() and then nextInt().

Related questions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值