我试图让用户选择菜单中的选项,并根据客户选择的选项设置变量,但当我转到另一个类并检索它时,没有传递任何值。
这是我的alacarte类
public class Alacarte {
public void alacarte(){
Checkout c = new Checkout();
System.out.println("Please select a meal");
System.out.println("\n1. Fried Chicken........9.90");
System.out.println("2. McChicken..........5.90");
System.out.println("3. Spicy Chicken McDeluxe......12.90");
System.out.println("\nOption:");
Scanner s = new Scanner(System.in);
int option = s.nextInt();
switch(option){
case 1:
this.order = "Fried Chicken";
this.price = 9.90;
c.receipt();
case 2:
this.order = "McChicken";
this.price = 5.90;
case 3:
this.order = "Spicy Chicken McDeluxe";
this.price = 12.90;
}
}
private String order;
private double price;
public double getPrice(){
return this.price;
}
public String getOrder(){
return this.order;
}
}这是我的checkout类
public class Checkout {
public void receipt(){
Alacarte as = new Alacarte();
System.out.println("Thank you for your order");
System.out.println("Your order is: " + as.getOrder());
System.out.println("The price is: " + as.getPrice());
System.out.println("\nThank you for ordering with us!");
}
}这是我的output
Thank you for your order
Your order is: null
The price is: 0.0
Thank you for ordering with us!发布于 2020-10-27 16:22:08
所有的信息你都在这里
this.order = "Fried Chicken";
this.price = 9.90;
c.receipt();因此,请更改receipt,使其具有参数
this.order = "Fried Chicken";
this.price = 9.90;
c.receipt(this.order, this.price);更改实现
public void receipt(String order, float price){
System.out.println("Thank you for your order");
System.out.println("Your order is: " + order);
System.out.println("The price is: " + price);
System.out.println("\nThank you for ordering with us!");
}发布于 2020-10-27 16:22:08
您在您的接收方法中创建了一个新的Alacarte实例,该实例不知道有关用户输入的任何信息。为此,一种方法是将数据作为参数传递给receipt方法。
c.receipt(this.order, this.price);在Checkout中:
public void receipt(String order, float price) {
System.out.println("Thank you for your order");
System.out.println("Your order is: " + order);
System.out.println("The price is: " + price);
System.out.println("\nThank you for ordering with us!");
}注意!在开关案例的末尾添加break语句,在末尾添加default语句。
https://stackoverflow.com/questions/64550319
复制相似问题