尝试重复直到条件为假 [英] Trying to repeat until condition is false

查看:24
本文介绍了尝试重复直到条件为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a loop that repeats until the user input correct information (no whitespaces or blank). This is what I have so far but it only repeats one time. I want it to repeat until user fills in a correct name, e.g. Oskar/OSKAR/oskar

    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 循环,这样你就不会写两次相同的代码:

You need to use a do/while loop so you don't write the same code twice:

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

输出:

输入您的姓名:
无效名称 "" 再试一次
输入您的姓名:a1
无效名称a1"重试
输入您的姓名:1
无效名称1" 再试一次
输入您的姓名:奥斯卡
欢迎奥斯卡

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

这篇关于尝试重复直到条件为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆