Skip to content
Advertisement

Variable value not being passed into another class

I’m trying to let the user to choose which option is in their menu, and setting the variables based on the option that the customer choose, but when I go to another class and retrieve it, there is no value being passed.

Here is my alacarte class

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;
    }

}

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

Here is my output

Thank you for your order
Your order is: null
The price is: 0.0

Thank you for ordering with us!

Advertisement

Answer

You have all the information here

        this.order = "Fried Chicken";
        this.price = 9.90;
        c.receipt();

so change receipt so that it has parameters

        this.order = "Fried Chicken";
        this.price = 9.90;
        c.receipt(this.order, this.price);

Change the implementation

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 People found this is helpful
Advertisement