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

 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 + AZ如何让扫描仪循环读取所需的字符串

我想使程序只接受男性或女性的输入而忽略案件,如果输入错误重复“输入性别:”直到输入正确的值。

回答:

你可以放一段代码,每次验证一次。例如:

String gender; 

do

{

System.out.print("Enter Gender ('male' or 'female'): ");

gender = one.nextLine().toLowercase();

} while(!gender.equals("male") && !gender.equals("female"))

回答:

do { 

System.out.print("Enter Gender (M/F): ");

gender = one.nextLine();

} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));

您可以添加后,如果性别分配检查显示无效的消息,要做到这一点

回答:

的一种方法是使用无限循环和标签打出来。
像这样:

//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");

}

}

回答:

公共类主要{

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);

}

以上是 如何让扫描仪循环读取所需的字符串? 的全部内容, 来源链接: utcz.com/qa/265246.html

回到顶部