-1
package order;

import java.util.Scanner;

public class Order {

    /*int fries = 5;
    int burger = 7;
    int soda = 4;
    int coffee = 3;
    int donut = 6;
    */
    double price;

    public static void printMenu(String[][] menu) {
        for(int rows = 0; rows < menu.length;rows++) {
            for(int columns = 0; columns < menu[rows].length;columns++) {
                System.out.println(menu[rows][columns]);
            }
        }
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    public void choose(double price) {
        this.price = price;
        Scanner sc = new Scanner(System.in);
        int menuNumber = sc.nextInt();

        switch(menuNumber) {
            case 1:
                System.out.println("You added fries");
                price = price + 5.00;
                break;
            case 2:
                System.out.println("You added a burger");
                price = price +7.00;
            case 3:
                System.out.println("You added a soda");
                price = price + 4.00;
            case 4:
                System.out.println("You added coffee");
                price = price + 3.00;
            case 5:
                System.out.println("You added donut");
                price = price + 6.00;
            default:
                System.out.println("You need to choose an order 1-5");

        }
    }
    public static void main(String[] args) {
        String[][] menu = {{"fries : $5.00","burger: $7.00","soda: $4.00","coffee: $3.00","donut: $6.00"}};
        printMenu(menu);
        choose(price);

    }
}

I am confused how to even call the setPrice method at all? I am trying to call it through the main method, but it gives me an error:(Cannot make a static reference to the non-static field price). What do I need to do to call the setPrice method?

Turing85
  • 18,217
  • 7
  • 33
  • 58

1 Answers1

1

Because main is a static method (i.e., it belongs to the class as a whole, and not any particular instance of a class), you must create an Order object in order to access or set the instance variable price from the main method.

I would initialize price to 0.0 in an Order constructor, since that will always be the starting value.

Then, in main, initialize an Order object and invoke choose to start adding items. There's no need to pass the price to the choose method because it is an instance variable of the order object just created.

Order order = new Order();
order.choose();

The reason this works is because we've now created an Order instance, allowing us to invoke non-static methods (i.e., methods that belongs to a particular class). You can also now invoke setPrice directly with order.

Clint
  • 900
  • 11
  • 25