当我输入值“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();
我很困惑为什么:“请输入学生姓:请选择主题单位:”也在同一行。
你能帮忙吗? 感谢答案 0 :(得分:3)
next()
方法从流中检索下一个标记,默认情况下由空格分隔。 next()
对名字的调用仅消耗Adam
。下一次调用next()
会消耗J
,让您处于第三次提示状态。
您应该拨打nextLine()
来检索整行,以便Adam J
一次性使用firstName
。
答案 1 :(得分:0)
case 1:
System.out.println("Please enter student first name: ");
firstName = scan.nextLine();
while(!firstName.matches("[a-zA-Z]+"))
{
System.out.println("Please enter a valid first name: ");
firstName = scan.nextLine();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.println("Please enter student surname: ");
lastName = scan.nextLine();
while(!lastName.matches("[a-zA-Z]+"))
{
System.out.println("Please enter a valid surname: ");
lastName = scan.nextLine();
}
surCap = lastName.substring(0,1).toUpperCase() + lastName.substring(1);
System.out.println("Please select Subject Unit: ");
unit = scan.nextLine();
我假设额外 - 你的正则表达式是无意的。另外,你的正则表达式应该检查[a-zA-Z] +而不是[a-zA-Z] *,因为空名对我来说似乎没有用。
答案 2 :(得分:-1)
尝试nextLine()
代替next()
。