gpt4 book ai didi

java - 当输入字母+空格+字母时,程序变得很有趣

转载 作者:行者123 更新时间:2023-12-02 04:43:56 26 4
gpt4 key购买 nike

当我为我的名字输入值“Adam J”时,会输出以下内容:

Please enter student first name: Adam J
Please enter student surname: Please select Subject Unit:

我希望它拒绝这个值,就像输入数字一样。理想情况下,如果其中有空格,我不希望它接受它,所以它会说“请输入有效的名字”。

 case 1:
System.out.print("Please enter student first name: ");
firstName = scan.next();

while(!firstName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid first name: ");
firstName = scan.next();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);

System.out.print("Please enter student surname: ");
lastName = scan.next();

while(!lastName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid surname: ");
lastName = scan.next();
}
surCap = lastName.substring(0,1).toUpperCase() + lastName.substring(1);

System.out.print("Please select Subject Unit: ");
unit = scan.next();

我很困惑为什么:“请输入学生姓氏:请选择科目单位:”也在同一行。

你能帮忙吗?谢谢

最佳答案

next() 方法从流中检索下一个标记,默认情况下由空格分隔。对名字的 next() 调用仅消耗 Adam。下一次调用 next() 会消耗 J,让您看到第三个提示。

您应该调用 nextLine() 来检索整行,以便 Adam J 一次性为 firstName 消耗。

关于java - 当输入字母+空格+字母时,程序变得很有趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29856112/

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