Skip to content
Advertisement

How do I add a method so I can just a String instead of typing a whole statement

how do i make it so i only have to type “onion” instead of typing the whole thing. I am trying add a String for the Flavour of PackOfCrisps, but i have to type:

new PackOfCrisps(“onion”)

this is what i have done for the method

public void addPack(PackOfCrisps pack) {
      if (packets.size() < capacity) {
         packets.add(pack);
         
      } 
      else {
         System.out.println("capacity reached");
      }
   }

and this is the interface i get where i have to type: new PackOfCrisps(“onion”)

Advertisement

Answer

Create a method that takes a String as an input and creates a PackOfCrisps out of it. You can then have that method use your already existing method to insert this new PackOfCrisps object.

public void addPackByFlavour(String flavour) {
    // create a new object with the given flavour
    PackOfCrisps pack = new PackOfCrisps(flavour);

    // insert that object by using the already existing method
    addPack(pack);
}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement