Michael Pnrs
Michael Pnrs

Reputation: 125

How can I set variables from a class of ArrayLists to the Main class?

I have already created an object and tried to set some variables but I cannot find the type of the variables that should I create in order to do not have any problem.

The part of the main class:

                Menu menu = new Menu();
                scanner.nextLine();
                System.out.println("Give a code.");
                String code =  scanner.nextLine();
                menu.setCode(code);
                System.out.println("Give a main dish");
                String MainDish = scanner.nextLine();
                menu.setMainDishes(MainDish);
                System.out.println("Give a drink.");
                String Drink = scanner.nextLine();
                menu.setDrinks(Drink);
                System.out.println("Give a sweet.");
                String Sweet = scanner.nextLine();
                menu.setSweets(Sweet);  

And the Menu class:

  public class Menu {
  ArrayList<String> MainDishes = new ArrayList<>();
  ArrayList<String> Drinks = new ArrayList<>();
  ArrayList<String> Sweets = new ArrayList<>();
  private String code;

  public ArrayList<String> getMainDishes() {
      return MainDishes;
  }

  public void setMainDishes(ArrayList<String> mainDishes) {
      MainDishes = mainDishes;
  }

  public ArrayList<String> getDrinks() {
    return Drinks;
  }

  public void setDrinks(ArrayList<String> drinks) {
      Drinks = drinks;
  }

  public ArrayList<String> getSweets() {
      return Sweets;
  }

  public void setSweets(ArrayList<String> sweets) {
      Sweets = sweets;
  }

  public String getCode() {
      return code;
  }

  public void setCode(String code) {
      this.code = code;
  }

Compliler give an error because of the String variables that I created.

Upvotes: 2

Views: 66

Answers (2)

TheWhiteRabbit
TheWhiteRabbit

Reputation: 1313

Your menu class contains ArrayList variables and you try to assign a String to them. Instead of:

menu.setMainDishes(MainDish);

Try:

menu.getMainDishes().add(MainDish);

Also, common convention in Java is to start variables with lowercase, eg mainDish.

Upvotes: 2

Derek Pendleton
Derek Pendleton

Reputation: 134

You are trying to pass a string when the methods are expecting an ArrayList of strings. If you want to do it the way you currently are, then create an ArrayList, put the user input into it, then pass that ArrayList to the methods that call for it.

Upvotes: 0

Related Questions