JAVA帮助获取输入的总和

标签 java loops input while-loop

我正在尝试编写一个JAVA代码,它不断接受整数,直到达到特定数字,因此之后,用户必须为剩余的输入输入0,以保持输入的总和<=条件

示例:如果我有 5 杯咖啡和 5 杯可用,则用户为第一杯咖啡输入 3 杯,然后为第二杯咖啡输入 2 杯。所以现在 3+2 = 5 杯,这是可用的咖啡杯数量,因此对于接下来的 3 杯咖啡,用户应该输入 0 继续,否则它会一直循环。

这就是我的代码的样子:

int add = 0;
int[] numberOfCoffeeShots = new int[coffeeCupsAvailable]; //input number of shots for every coffee cup
int i; //declares i

 for (i = 0; i < coffeCupsWanted; i++) { //iterate over a range of values.
 System.out.print("How many coffee shots in cup " + (i + 1) + "? ");
 numberOfCoffeeShots[i] = keyboard.nextInt();
 add += (numberOfCoffeeShots[i]); //adding the number of shots in each cup

while (numberOfCoffeeShots[i] < 0) {
System.out.println("Does not compute. Try again.");
System.out.print("How many coffee shots in cup " + (i + 1) + "? ");
numberOfCoffeeShots[i] = keyboard.nextInt();
}    

 while (numberOfCoffeeShots[i] > coffeeShotsAvailable) {
 System.out.println("There are only " + coffeeShotsAvailable + " coffee shots left. Try again.");
  System.out.print("How many coffee shots in cup " + (i + 1) + "? ");
  numberOfCoffeeShots[i] = keyboard.nextInt();
 }

我仍然需要 while 循环来计算输入总和 > CoffeeShotsAvailable

关于这个想法有什么帮助吗?谢谢

最佳答案

这是我的解决方案。这段代码下面是该程序的完整演练及其工作原理。

public class CoffeeAndShots{

    public static void main(String[] args){

        Scanner keyboard = new Scanner(System.in);

        int numberOfCoffees = 5;
        int numberOfShots = 5;
        int[] coffeeShots = new int[numberOfCoffees];

        for(int i = 0; i < numberOfCoffees; i++)
            coffeeShots[i] = -1;

        for(int i = 0; i < numberOfCoffees; i++){
            int input;
            while(coffeeShots[i] < 0){
                System.out.println("How many shots for coffee cup " + (i + 1) + "?");
                input = keyboard.nextInt();
                if(input > numberOfShots)
                    System.out.println("You don't have that many shots");
                else{
                    coffeeShots[i] = input;
                    numberOfShots = numberOfShots - input;
                }
            }
        }

        for(int i = 0; i < numberOfCoffees; i++)
            System.out.println(coffeeShots[i] + " shots for coffee cup " + (i + 1));
    }


}

coffeeShots 是一个整数数组,其初始化的项数等于我们正在使用的咖啡杯的数量。在紧随其后的 for 循环中,该数组中的每个项都设置为 -1。这是因为在程序的后面,用户可能不会为特定的咖啡杯分配任何镜头。在下一个 for 循环中,我们遍历咖啡杯数组中的每个术语。对于每个杯子,我们将询问用户他们想要该杯子的拍摄次数,直到接受大于或等于 0 的值。在接受值时,我们需要确保指定的镜头数量实际上可用。如果是,我们将该杯子的射击次数设置为输入的值,然后从我们分配的数量中扣除我们的总射击次数。当一切都说完了之后,我们打印整个数组。

关于JAVA帮助获取输入的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36491260/

相关文章:

css - 强制标签与他们标记的输入内联流动

objective-c - 让用户从 Mac OS X 应用程序安装 Java

java - URLClassLoader 和包私有(private)方法的可访问性

java - 具有多个连接列的 OneToMany 关系

Javascript:创建循环来检查变量是否为 int

perl - 在 Perl 中读取输入文件并将其放入带有空格分隔符的数组中

java - 使用 apache poi 通过流/分页策略将 xlsx 文件解析为 block

C - 文件 IO 读写错误

C++ 循环算法逻辑问题

jquery - 空输入返回 false 仅适用于一个输入,不适用于两个输入