[英]Get a value of a variable of a class instance while being at another class instance
[英]Variable value not being passed into another class
我试图让用户选择菜单中的选项,并根据客户选择的选项设置变量,但是当我将 go 转换为另一个 class 并检索它时,没有传递任何值。
这是我的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
class
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!
你有这里的所有信息
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!");
}
您在收据方法中创建了一个新的 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!");
}
注意。 在 switch case 末尾添加 break 语句,在末尾添加 default 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.