当 Do/While 完成时,Java 输入停止工作

我正在尝试创建一个运行循环,用户可以在其中输入进入/离开牡蛎条的牡蛎,直到容量达到 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);


    }


}

任何输入将不胜感激,谢谢!


慕森卡
浏览 207回答 2
2回答

梵蒂冈之花

假设你想永远循环,你需要检查容量不足和过剩do {&nbsp; &nbsp; oystersIn=0;&nbsp; &nbsp; System.out.println("How many oysters are coming in?");&nbsp; &nbsp; oystersIn = input.nextInt();&nbsp;&nbsp; &nbsp; if (oystersIn + currentCapacity >= 500) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Sorry full - waiting for some one to leave");&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; if (oystersIn + currentCapacity < 0) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Can't go negative");&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; currentCapacity += oystersIn;&nbsp; &nbsp; System.out.println("Now there are " + currentCapacity + " oysters in the bar");}while (true);

江户川乱折腾

我建议你:-1)运行另一个 do while 循环,它接受负输入。2)如果你想在牡蛎不再可用的情况下重新运行程序并使用“break”,请将两个循环置于无限循环中;从无限循环中出来。&nbsp;希望这可以帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java