循环回到顶部?

我试图在地址中输入错误的内容以重复“您住在哪里?”的问题 使用 while 方法,但它似乎不再起作用了。


import java.util.Scanner;


public class ImScrewed {


    public static void main(String[] args) {

        boolean flag = true;


        Scanner scan = new Scanner(System.in);


        while (flag) {

            System.out.println("== Welcome to UwU Cafe! ==");

            System.out.print("What is your name? [Starts with 'Mr. ' or 'Ms. '] : ");

            String name = scan.nextLine();


            if (name.startsWith("Ms. ") || name.startsWith("Mr. ")) {

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

                flag = false;

            } else {

                System.out.println("Please re-enter your name");

            }

        }


        System.out.println("Where do you live? [Contains 'Street']");

        String address = scan.nextLine();


        if (address.contains("Street")) {

            System.out.println("Proceed to the next step");

            flag = false;

        } else {

            System.out.println("Please re-enter your address");

        }

    }

}


慕侠2389804
浏览 108回答 1
1回答

繁花不似锦

如果出现错误,您需要循环返回。在布尔变量和简单的 while 循环的帮助下,应该没问题。像这样的东西:boolean flag = true;do {    String name = scan.nextLine();    if (name.startsWith("Ms. ") || name.startsWith("Mr. ")) {        System.out.println("Welcome : " + name);        // break the loop.        flag = false;    } else {        System.out.println("Please re-enter your name");    } } while (flag);您也可以消除该变量。通过做类似的事情:while (true) {    String name = scan.nextLine();    if (name.startsWith("Ms. ") || name.startsWith("Mr. ")) {        System.out.println("Welcome : " + name);        break;    } else {        System.out.println("Please re-enter your name");    }}编辑:支持或多个字段。// previous while loop hereflag = true; // resetting flagwhile (flag) {    System.out.println("Where do you live? [Contains 'Street']");    String address = scan.nextLine();    if (address.contains("Street")) {        System.out.println("Proceed to the next step");        // terminate the loop        flag = false;    } else {        System.out.println("Please re-enter your address");    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java