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

Time:11-06

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")

CodePudding user response:

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

  • Related