简体   繁体   中英

Java: I can't get it to loop, somethings wrong with the boolean but I don't know how to fix it

public class Main {

public static void main(String[] args)throws Exception {
    Boolean yn;
    String answer;
    String name;

    do{
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your name");
        name = in.nextLine();
        System.out.println("Hi "+name);
        System.out.println("Do you want to enter another name?");
        System.out.println("y/n?");
        answer = in.nextLine().toLowerCase();
            if(answer.equals("y")){
                yn = true;
                break;
            }else if(answer.equals("n")){
                yn = false;
                break;
            }


    }while(yn = true );


}
}

i have to make it go back to asking the name when i get a yes for the last question. super noob here sorry please help.

Your break is the culprit...

When you use break it breaks out of the loop.

So use, (Note: You don't need an else if, just else should be sufficient).

        if(answer.equals("y")){
            yn = true;
        } else {
            yn = false;
        }

without break statement.

Also use a condition (not assignment) inside while,

while(yn == true)

or simply,

while(yn)

break不应该在被使用if只是如果你想关闭语句loop ,取出breakif

use continue instead of break as below

if(answer.equals("y")){
    yn = true;
    break;  //use continue here
} else if(answer.equals("n")){
    yn = false;
    break;
}

You can do this :

public static void main(String[] args)throws Exception {
Boolean yn;
String answer;
String name;
do {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your name");
        name = in.nextLine();
        System.out.println("Hi "+name);
        System.out.println("Do you want to enter another name?");
        System.out.println("y/n?");
        answer = in.nextLine().toLowerCase();
            if(answer.equals("y")){
                yn = true;
                continue;   //Continue does not terminate the loop instead of break
            }else {
                yn = false;
                break;
            }
    }while(yn = true );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM