gpt4 book ai didi

当 Do/While 满足时 Java 输入停止工作

转载 作者:行者123 更新时间:2023-12-02 10:46:26 25 4
gpt4 key购买 nike

我正在尝试创建一个运行循环,用户可以输入牡蛎进入/离开牡蛎吧,直到容量达到 500。

当容量达到 500 时,我希望用户仍然能够输入负数(因为顾客仍然可以离开),但不能输入任何正数。不幸的是,一旦满足条件,我就无法输入任何内容。

    Scanner input = new Scanner(System.in);
int maxCapacity = 500;
int oystersIn = 0;
int oystersOut;
int currentCapacity = 0;
System.out.println("Welcome to the Half Shell Dive Bar, Capacity is 500, and there are currently "+ currentCapacity + " oysters in the bar" );
currentCapacity = 0;
do {
oystersIn=0;
System.out.println("How many oysters are coming in?");
oystersIn = input.nextInt();
currentCapacity += oystersIn;
System.out.println("Now there are " + currentCapacity + " oysters in the bar");
}
while (oystersIn + currentCapacity <= 500);

}

}

任何意见都将不胜感激,谢谢!

最佳答案

假设你想永远循环,你需要检查容量是否不足和过多

do {
oystersIn=0;
System.out.println("How many oysters are coming in?");
oystersIn = input.nextInt();
if (oystersIn + currentCapacity >= 500) {
System.out.println("Sorry full - waiting for some one to leave");
continue;
}
if (oystersIn + currentCapacity < 0) {
System.out.println("Can't go negative");
continue;
}
currentCapacity += oystersIn;
System.out.println("Now there are " + currentCapacity + " oysters in the bar");
}
while (true);

关于当 Do/While 满足时 Java 输入停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52527860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com