gpt4 book ai didi

java - 尝试重复直到条件为假

转载 作者:行者123 更新时间:2023-11-29 06:55:49 25 4
gpt4 key购买 nike

我正在尝试制作一个循环,重复直到用户输入正确的信息(没有空格或空白)。这是我到目前为止所拥有的,但它只重复一次。我希望它重复直到用户填写正确的名称,例如奥斯卡/奥斯卡/奥斯卡

    System.out.print("Name: ");
String name = scanner.nextLine();
name = name == null ? "" : name.trim();
while(name.isEmpty()) {
System.out.println("Wrong data");
System.out.print("Name: ");
String name1 = scanner.nextLine();
name = name1;
}

最佳答案

您需要使用 do/while 循环,这样您就不会将相同的代码写两次:

Scanner scanner = new Scanner(System.in);

String name = null;
do { //use do while loop for this
if (name != null)
System.out.println("Invalid Name \"" + name + "\" Try again");

System.out.print("Enter Your Name: ");
name = scanner.nextLine();

//keep looping until name is only letters
} while (!name.matches("[A-Za-z]+"));

System.out.println("Welcome " + name);

输出:

Enter Your Name:
Invalid Name "" Try again
Enter Your Name: a1
Invalid Name "a1" Try again
Enter Your Name: 1
Invalid Name "1" Try again
Enter Your Name: Oskar
Welcome Oskar

关于java - 尝试重复直到条件为假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34494337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com