我相信我可能需要使用而不是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);
}
}
你將不得不解釋發生了什麼?什麼是輸入和輸出是什麼? –
您循環直到用戶輸入10,然後結束循環。在那個時候,這個數字是'10',你把它加到你的初始總和'0'中以得到'10'。 –