2016-09-27 51 views
-2

我相信我可能需要使用而不是while,但我不確定如何解決此問題。當我試圖研究這一切時,我能找到的是與「數組總和」有關的數據。儘管我已經聲明瞭這些值,但我的總和仍然等於10。有人可以幫忙嗎?謝謝我無法獲得總和來計算。我甚至不確定我的邏輯是否正確

public class OnlinePurchases { 
public static void main(String[] args) { 
    // TODO code application logic here 

    String sName = " "; 
    int nChoices = 0; 
    int nChoice1 = 249; 
    int nChoice2 = 39; 
    int nChoice3 = 1149; 
    int nChoice4 = 349; 
    int nChoice5 = 49; 
    int nChoice6 = 119; 
    int nChoice7 = 899; 
    int nChoice8 = 299; 
    int nChoice9 = 399; 
    int nSum = 0; 
    final int SENTINEL = 10; 
    int nCount = 0; 

    Scanner input = new Scanner(System.in); 

    System.out.print("Please enter your name : "); 
    sName = input.nextLine(); 

    System.out.println("BEST PURCHASE PRODUCTS \n"); 
    System.out.println("1. Smartphone $249"); 
    System.out.println("2. Smartphone case $39"); 
    System.out.println("3. PC Laptop $1149 "); 
    System.out.println("4. Tablet $349"); 
    System.out.println("5. Tablet case $49"); 
    System.out.println("6. eReader $119"); 
    System.out.println("7. PC Desktop $899"); 
    System.out.println("8. LED Monitor $299"); 
    System.out.println("9. Laser Printer $399"); 
    System.out.println("10. Complete my order"); 

    System.out.println(""); 

    System.out.print("Please select an item from the menu above : "); 
    nChoices = input.nextInt(); 

    while (nChoices != SENTINEL) { 
    System.out.print("Please select another item from the menu above : "); 

    nCount++; 

    nChoices = input.nextInt(); 

    if (nChoices == 1) { 
    nChoices = nChoice1; 
    } else if (nChoices == 2) { 
    nChoices = nChoice2; 
    } else if (nChoices == 3) { 
    nChoices = nChoice3; 
    } else if (nChoices == 4) { 
    nChoices = nChoice4; 
    } else if (nChoices == 5) { 
    nChoices = nChoice5; 
    } 
    } 

    nSum = nSum + nChoices; 
    System.out.println("Price of Items Ordered : " + nSum); 
    System.out.println("Total Items Ordered : " + nCount); 
} 
} 
+4

你將不得不解釋發生了什麼?什麼是輸入和輸出是什麼? –

+1

您循環直到用戶輸入10,然後結束循環。在那個時候,這個數字是'10',你把它加到你的初始總和'0'中以得到'10'。 –

回答

0

您的while循環很好。

您的問題發生,因爲當選擇選擇時,你實際上並沒有添加到你的nSum變量。因此,當涉及到印刷和出你實際上是在打印

nSum = nSum + nChoices = nSum = 0 + 10 

這就是爲什麼你經常收到價值10

爲了解決這個問題更換您的nChoices if語句

if (nChoices == 1) { 
    nSum += nChoice1; 
} else if (nChoices == 2) { 
    nSum += nChoice2; 
} else if (nChoices == 3) { 
    nSum += nChoice3; 
} else if (nChoices == 4) { 
    nSum += nChoice4; 
} else if (nChoices == 5) { 
    nSum += nChoice5; 
} 
0

您正在使用變量nChoices檢查輸入的數字。當你想停止程序時,10是最後輸入的數字,所以10是添加到nSum中的數字。爲了解決這個問題,你應該首先在輸入while循環之前檢查第一個輸入,然後在while循環結束時檢查輸入,這樣如果選擇了10,它將不會再次通過循環。此外,在每個if/else if語句下,您應該使用:

nSum += nChoiceWhatever //"Whatever" being the number correlated to your prices