2016-04-08 61 views
0

我想寫一個JAVA代碼,它保持接受整數,直到達到一個特定的數字,所以在這之後,用戶必須輸入0爲剩餘的輸入,以保持總和的輸入< =條件JAVA幫助獲取輸入總和

例如:如果我有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(); 
} 

我仍然需要投入的總和,而循環> coffeeShotsAvailable

任何幫助,請這個想法?謝謝

+0

[JAVA輸入的總和大於特定條件未接受]的可能重複(http://stackoverflow.com/questions/36479536/java-sum-of-inputs-greater-than-a-specific-condition-unaccepted ) –

+0

我知道我想刪除舊的1抱歉 –

回答

1

這是我的解決方案。在這個代碼下面是一個完整的演示程序和它的工作原理。

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的值。在接受數值時,我們需要確保指定的鏡頭數量實際上可用。如果是,我們將該杯子的投籃數量設置爲輸入值,然後根據我們分配的數量扣除我們的總投籃數。說完之後,我們打印整個陣列。

+0

非常感謝! –