我试图让用户选择菜单中的哪个选项,并根据客户选择的选项设置变量,但是当我进入另一个类并检索它时,没有传递任何值
这是我的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!
答案 0 :(得分:1)
您在这里拥有所有信息
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!");
}
答案 1 :(得分:-1)
您正在使用收据方法创建Alacarte的新实例,该实例对用户输入一无所知。一种方法是将数据作为参数传递给接收方法。
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!");
}
NB!在转换案例的末尾添加break语句,并在末尾添加default。