完成“完成/完成”操作后,Java输入停止工作

时间:2018-09-27 00:44:07

标签: java loops

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

    }

}

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

2 个答案:

答案 0 :(得分:1)

假设您要一直循环下去,则需要检查容量是否过大

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

答案 1 :(得分:0)

我建议您:-
1)运行另一个执行do的while循环,该循环需要负输入。 2)如果想要重新运行程序(如果不再有牡蛎的话),则将两个循环都置于无限循环中,并且 用“ break”从无限循环中走出来。 希望这会有所帮助