我正在尝试编写一个JAVA代码,它一直接受整数,直到达到一个特定的数字,所以在此之后,用户必须为剩余的输入输入0,以保持输入的总和&lt; = condition < / p>
示例:如果我有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循环&gt; coffeeShotsAvailable
任何有关这个想法的帮助?感谢
答案 0 :(得分:2)
这是我的解决方案。在此代码下面是该程序的完整演练及其工作原理。
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的值。在接受值时,我们需要确保指定的镜头数实际可用。如果是,我们将该杯子的拍摄数量设置为输入值,然后按照我们分配的数量扣除我们的总拍摄数量。完成后,我们打印整个阵列。