Java >> Java チュートリアル >  >> Tag >> 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 です クラス

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!");
}

Java タグ