【问题标题】:Java how to end a do-while loop using boolean input from user?Java如何使用来自用户的布尔输入来结束do-while循环?
【发布时间】:2016-03-04 13:50:30
【问题描述】:

所以我想让用户输入“真”或“假”来退出循环。正如我现在拥有的那样,无论我输入什么,它都会退出循环。

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

顺便说一句,是的,这是一个关于颜色保护的程序

【问题讨论】:

  • 替代:while(correct == false)

标签: java loops boolean do-while


【解决方案1】:

correct = false 是一个作业。

您应该使用!correct 来测试correct 是否为false

示例代码;

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

如果你想要其他方式

do {
    //
}
while(correct);
//while(correct == true)

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多