我做了一个简单的程序,允许用户输入一个名字然后问候他。
import java.util.Scanner;
public class nameinput {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a name: (only letters, at least 2 characters long)");
while (true) {
String name= sc.next();
if (name.length() < 2){
System.out.println("This name is too short!");
continue;
}
else if (!name.matches("[a-zA-Z]+")){
System.out.println("Letters only!");
continue;
}
else {
System.out.println("Hello, " + name);
break;
}
}
}
}
但是我有两个问题我无法解决:
我希望我能清楚地描述问题,提前感谢您的帮助!
答案 0 :(得分:4)
如果您只是将sc.next
替换为sc.nextLine()
。 nextLine将捕获所有按键,直到按下输入。
答案 1 :(得分:1)
import java.util.Scanner;
public class nameinput {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a name: (only letters, at least 2 characters long)");
while (true) {
String name= sc.nextLine();
if (name.length() < 2){
System.out.println("This name is too short!");
continue;
}
else if (!name.matches("[a-zA-Z]+")){
System.out.println("Letters only!");
continue;
}
else {
System.out.println("Hello, " + name);
break;
}
}
}
}