简体   繁体   中英

Java how to end a do-while loop using boolean input from user?

So I want to have a user input either "true" or "false" to exit the loop. As I have it now, it exits the loop no matter what I type.

public static void main(String[] args) {
    // Color guard flags
    Scanner kb = new Scanner(System.in);
    Flag yourFlag;
    double weight;
    boolean correct;
    do {
        System.out.println("Hello!\nWhat colors are your silk? (most common two)\nHow long is your pole (in feet)?"
                + "\nWhat have you named your flag?\nHow heavy is your flag (in pounds)?");
        yourFlag = new Flag(kb.next(), kb.next(), kb.nextInt(), kb.next(), kb.nextDouble());
        if (yourFlag.getWeight() >= 7) {
            System.out.println("That sounds like a cool flag! It sounds pretty heavy though.");
        } else {
            System.out.println("That sounds like a cool flag!");
        }
        System.out.println("You've entered that your flag " + yourFlag.getName() + " is " + yourFlag.getWeight() + " pounds and "
                + yourFlag.lengthOfPole + " feet long. It also has the pretty colors " + yourFlag.silkColor1 + " and " + yourFlag.silkColor2);
        System.out.println("Is that correct? (True or flase)");
        correct = kb.nextBoolean();
    }
    while (correct = false);

Btw, yes this is a program about color guard

correct = false is an assignment.

You should use !correct to test if correct is false .

sample code;

do {
    //
}
while(!correct);
//while(correct == false)

and if you want it otherway

do {
    //
}
while(correct);
//while(correct == 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