该程序提示用户输入汉堡包,沙拉,法式炸薯条和苏打水的数量,然后显示该订单的总数。该应用程序应包括一个带有构造器的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);
}
}
最佳答案
您不需要第二类的totalCost,因为Food对象是单个实体,不会保留所有已创建对象的运行总数
话虽如此,这种方法似乎是正确的
double totalCost = 0;
Food hamburger = new Food(1.85, 9.0, 33, 1);
totalCost += hamburger.getPrice() * hamburgerTotal;
// get more food
System.out.print(totalCost);
总成本定义为商品数量乘以价格
并且构造函数不需要任何总值,因为该总值未包含在描述中
具有构造函数的食物对象,该构造函数接受商品的价格,脂肪,碳水化合物和纤维
public Food (double nPrice, double nFat, double nCarb, double nFiber) {
price = nPrice;
fat = nFat;
carb = nCarb;
fiber = nFiber;
}