【发布时间】:2019-11-26 22:21:44
【问题描述】:
程序提示用户输入汉堡包、沙拉、薯条、薯条和苏打水的数量,然后显示订单的总数。应用程序应该包含一个带有构造函数的 Food 对象,该构造函数接受一个项目的价格、脂肪、碳水化合物和纤维。食用方法 应该返回商品的价格并返回脂肪、碳水化合物和纤维。打印的行应该是总成本,但它一直打印总成本为 0 美元。问题是累积成本的变量在第二类中没有更新。
import java.util.Scanner;
import java.lang.String;
import java.text.NumberFormat;
public class LunchOrder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double totalCost = 0;
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.print("Enter number of hamburgers: ");
double hamburgerTotal = input.nextInt();
Food foodOne = new Food("Hamburger", 1.85, 9.0, 33, 1, hamburgerTotal);
System.out.println(foodOne + "\n");
totalCost += hamburgerTotal * 1.85;
totalCost += foodOne.getTotalCost();
System.out.print("Enter number of salads: ");
double saladTotal = input.nextInt();
Food foodTwo = new Food("Salad", 2.00, 1, 11, 5, saladTotal);
System.out.println(foodTwo + "\n");
totalCost += saladTotal * 2.00;
totalCost += foodTwo.getTotalCost();
System.out.print("Enter number of french fries: ");
double frenchFrieTotal = input.nextInt();
Food foodThree = new Food("French fries", 1.30, 11, 36, 4, frenchFrieTotal);
System.out.println(foodThree + "\n");
totalCost += frenchFrieTotal * 1.30;
totalCost += foodThree.getTotalCost();
System.out.print("Enter number of sodas: ");
double sodaTotal = input.nextInt();
Food foodFour = new Food("Soda", 0.95, 0, 38, 0, sodaTotal);
System.out.println(foodFour + "\n");
totalCost += sodaTotal * 0.95;
totalCost += foodFour.getTotalCost();
System.out.println(foodFour.setPrice());
}
}
class Food {
String item;
double price;
double fat;
double carb;
double fiber;
double total;
double foodTotal;
double totalCost;
NumberFormat money = NumberFormat.getCurrencyInstance();
public Food (String nItem, double nPrice, double nFat, double nCarb, double nFiber, double hamburgerTotal) {
item = nItem;
price = nPrice;
fat = nFat;
carb = nCarb;
fiber = nFiber;
foodTotal = hamburgerTotal;
totalCost = totalCost +(price * foodTotal);
}
public void total() {
double totalCost = price * foodTotal;
totalCost += (price * foodTotal);
System.out.println(money.format(totalCost));
}
public double getTotalCost(){
return totalCost;
}
public String setPrice() {
String priceString;
priceString = "Your order comes to: " + totalCost;
return(priceString);
}
public String toString() {
String orderString;
orderString = "Each " + item + " has " + fat + "g of fat, "
+ carb + "g of carbs, and " + fiber + ".g of fiber.";
return(orderString);
}
}
【问题讨论】: