[英]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.