对于您是否输入.hasNextInt()
之类的数字而言,Java很容易,但是String
呢?
do {
System.out.println("Please enter the students name: ");
String name = s.nextLine();
if (name.equalsIgnoreCase("Done")) {
finished = true;
} else {
System.out.println("Please input the students number");
int studentNo = s.nextInt();
System.out.println("Please enter that students subject: ");
String subject = s.next();
System.out.println("Pleae enter that students level- ");
int level = s.nextInt();
StudentRecords newStudent = new StudentRecords(name, studentNo, subject, level);
studentRecordList.add(newStudent);
}
} while (!finished);
我如何让它循环以确保用户为学生姓名输入String
,而不是int
等。
谢谢。
答案 0 :(得分:3)
使用Regex尝试以下循环:
String name="";
while(!name.matches("[a-zA-Z \'\-ÄäÖöÜüßÉéæø]+")){
System.out.println("Please enter the student name: ");
name = s.nextLine();
}
这将询问用户输入,直到给出有效名称。
答案 1 :(得分:1)
关于我的评论,这样的事情将会起作用:
if(!name.matches(".*\\d.*")){
//It is correct name, because it does not contain any integer.
} else{
//retry getting name from user because it contains integer.
}
编辑评论问题:上面的代码会检测输入是否包含任何整数,但是如果你想检查它是否包含字符,你可以使用它:
!name.matches("[a-zA-Z ]+")
答案 2 :(得分:0)
你可以使用只允许字母和空格的regular expression:
boolean nameIsValid = false;
while (!nameIsValid)//while name is not valid
{
System.out.println("Please enter the students name: ");
String name = s.nextLine();
if (name.matches("[A-Za-z ]*"))//match only letters/spaces
nameIsValid = true;//we have a valid name, we may now break out of the loop
else
System.out.println("Please enter a valid name!");//invalid name, loop again
}