我只是第一年大學生和我的項目正在創建一個訂購系統,但我堅持定價,因爲我不能做總價。當程序循環時,它計算出價格錯誤。 A1和A2是我輸入的唯一選擇,因爲這仍然是一個未完成的項目。如何在Java訂購系統中計算總價格?
import java.io.*;
public class Ordering_System
{
public static void main(String []args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String order,again;
int quantity,price1=0,price2=0,loop1=0,quantity1,quantity2=0;
System.out.println(" ");
System.out.println("Welcome to MgRonalds, What do you want to order?");
System.out.println(" ");
System.out.println("*******************************************************************");
System.out.println("* Code Meal ''MENU'' Price *");
System.out.println("* *");
System.out.println("* (A1) MgBurger P30.00 *");
System.out.println("* (A2) Big Mac P139.00 *");
System.out.println("* (B1) Cheese Burger P35.00 *");
System.out.println("* (B2) Chicken Burger P50.00 *");
System.out.println("* (C1) MgNuggets P65.00 *");
System.out.println("* (C2) MgChicken P79.00 *");
System.out.println("* (D1) MgSpagetti P60.00 *");
System.out.println("* (D2) MgFries P40.00 *");
System.out.println("* (E1) Coke P10.00 *");
System.out.println("* (E2) Sprite P10.00 *");
System.out.println("* (E3) Royal P10.00 *");
System.out.println("* (F1) Sundae P25.00 *");
System.out.println("* (F2) MgFloat P25.00 *");
System.out.println("* *");
System.out.println("*******************************************************************");
do{
System.out.println("");
System.out.print("Enter Code Order : ");
order=br.readLine();
if (order.equalsIgnoreCase("A1")) {
price1=30;
System.out.println("Order Description : MgBurger ");
} else if (order.equalsIgnoreCase("A2")) {
price1=139;
System.out.println("Order Description : Big Mac ");
}
System.out.print("Enter Quantity : ");
quantity1= Integer.parseInt(br.readLine());
quantity2=quantity1+quantity2;
price2=price1*quantity2;
System.out.print("Another Order? (Y/N) : ");
again=br.readLine();
if (again.equalsIgnoreCase("y"))
loop1=loop1+1;
else loop1=loop1-100;
} while (loop1==1);
System.out.println(" ");
System.out.println("Total Price : "+price2);
}
}
下面是一個例子輸出:
Enter Code Order : a1
Order Description : MgBurger
Enter Quantity : 2
Another Order? (Y/N) : y
Enter Code Order : a2
Order Description : Big Mac
Enter Quantity : 2
Another Order? (Y/N) : n
Total Price : 556
答案應該是338不是556
我建議在調試器中逐步調試代碼,並在執行代碼期間觀察值。我敢打賭,你會很快找到你基於錯誤值計算事物的位置:)另外,如果你給變量賦予更多的描述性名稱,比如'totalPrice'和'priceForCurrentItem'等,它會幫助你當你在錯誤的地方使用你的變量時,它更加清晰。 – Krease 2014-10-03 23:10:08
我從來不知道'麥當勞'有一個新的特許經營'MgRonalds'! :p – 2014-10-03 23:24:11