我需要添加飲料的所有費用,直到輸入5才能退出程序。我該如何去做呢?當我運行這個程序時,它只顯示最後一個訂單的總數,而不是全部訂單。如何使用while while循環添加輸出?
import java.util.Scanner;
public class Beverage
{
// Constants
static final double COSTOFCOFFEE = 1.00;
static final double COSTOFTEA = .75;
static final double COSTOFCHOCOLATE = 1.25;
static final double COSTOFCAPPUCCINO = 2.25;
static final double tax = 0.06;
public static void main(String[] args)
// This method determines the type & amount of beverages desired
{
Scanner keyboard=new Scanner(System.in);
double cost = 0; // cost of the beverages
int numberOfCups = 0; // number of cups desired
int bevType; // type of beverage selected
double totalcost = 0 ;
do
{
System.out.println("Hot Beverage Menu");
System.out.println("Please select a choice from the following");
System.out.println("1: Coffee");
System.out.println("2: Tea");
System.out.println("3: Hot Chocolate");
System.out.println("4: Cappuccino");
System.out.println("5: EXIT ");
bevType = keyboard.nextInt();
if (bevType < 5 && bevType > 0)
{
System.out.println("How many cups would you like?");
numberOfCups = keyboard.nextInt();
}
switch(bevType)
{
case 1 : cost = numberOfCups * COSTOFCOFFEE;
break;
case 2 : cost = numberOfCups * COSTOFTEA;
break;
case 3 : cost = numberOfCups* COSTOFCHOCOLATE;
break;
case 4 : cost = numberOfCups * COSTOFCAPPUCCINO;
break;
case 5 : System.out.println("Thanks for your order");
totalcost = totalcost + cost;
break;
default : System.out.println("Invalid Selection");
}
if (bevType == 1 || bevType == 2 || bevType == 3 || bevType == 4)
System.out.printf("The total cost is $%.2f \n" , cost);
}while (bevType!=5);
if(bevType == 5)
System.out.println("The total cost of all beverages is " +totalcost);
keyboard.close();
}
}
請格式化這個更好,並刪除多餘的空格。 – ergonaut