如何让扫描仪循环直到它读取所需的字符串?

时间:2015-04-16 18:02:39

标签: java java.util.scanner

        Scanner one = new Scanner(System.in);
        System.out.print("Enter Name: ");
        name = one.nextLine();
        System.out.print("Enter Date of Birth: ");
        dateofbirth = one.nextLine();
        System.out.print("Enter Address: ");
        address = one.nextLine();  
        System.out.print("Enter Gender: ");
        gender = //not sure what to do now

您好我已经尝试过自己解决这个问题,但是我不能通过查看其他示例来获取它,大多数只是接受某些字符或A-Z + a-z

我试图让程序只接受男性或女性的输入忽略该情况,如果输入错误则重复"输入性别:"直到输入正确的值。

4 个答案:

答案 0 :(得分:6)

您可以暂时放置这段代码并进行验证。例如:

String gender;
do
{
  System.out.print("Enter Gender ('male' or 'female'): ");
  gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))

答案 1 :(得分:2)

do {
    System.out.print("Enter Gender (M/F): ");
    gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));

您可以在性别分配后添加if检查以显示无效消息

答案 2 :(得分:1)

这样做的一种方法是使用无限循环和标签来突破 像这样:

//Start 
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
    String str = one.nextLine();
        switch (str.toUpperCase()){
            case "MALE":
                System.out.println("Cool");
                break here;
            case "FEMALE":
                System.out.println("Nice");
                break here;
            default:
                System.out.println("Genders variants: Male/Female");
      }
}

答案 3 :(得分:1)

public class Main {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter Name: ");
    String name = readValue(scanner, null);
    System.out.print("Enter Date of Birth: ");
    String dateofbirth = readValue(scanner, null);
    System.out.print("Enter Address: ");
    String address = readValue(scanner, null);
    System.out.print("Enter Gender: ");
    String gender = readValue(scanner, createGenderMatcher());
}

private static IMatcher createGenderMatcher() {
    return new IMatcher() {
        @Override
        public boolean isMatch(String value) {
            return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
        }
    };
}

private static String readValue(Scanner scanner, IMatcher matcher) {
    String value = null;
    do {
        value = scanner.nextLine();
    } while (matcher != null && !matcher.isMatch(value));
    return value;
}

private interface IMatcher {
    public boolean isMatch(String value);
}