Frage

I have one single method that takes in 2 parameters:

public void generate(int size, String animal){
      // output a picture of the "animal" on java.swing of size "size"
}

So the possibility of the animals are Monkey, Giraffe, Dog, Cat, and Mouse. However, the assignment specifies that I can only have 1 method, no if-statements / cases / ternary operators, no external classes. So in the method, I have to create all 5 of these animals:

public void generate(int size, String animal){
      // output picture of Monkey
      // output picture of Giraffe
      // output picture of Dog
      // output picture of Cat
      // output picture of Mouse
}

So in turn, I was thinking I have to only make part of the method run based on the inputs. Is there any way to do this? The professor's hint was to use "multiple dispatch", but if there is only 1 method, how is this possible?

War es hilfreich?

Lösung

public interface Animal {
   public void draw(int size);
}

public class Monkey implements Animal {
   public void draw(int size) {
      // ...
   }
}

etc.

Andere Tipps

Since you do not want to use if/else/switch-case , assuming each type of animal is a class you can try this implementation.

public class Test {

static Map<String, Animal> animalTypeMap = new HashMap<String, Animal>();
static {
    animalTypeMap.put("Monkey", new Monkey());
    // put other animals in the map

}

public static void main(String[] args) {

    Test test = new Test();
    test.generate(5, "Monkey");

}

public void generate(int size, String animal) {
    // output picture of Monkey
    Animal animalObj = animalTypeMap.get(animal);
    animalObj.draw(size);
    // output picture of Giraffe
    // output picture of Dog
    // output picture of Cat
    // output picture of Mouse
}

}

interface Animal {
public void draw(int size);
// .....more methods

}

class Monkey implements Animal {

// ...implement methods
@Override
public void draw(int size) {
    System.out.println("Monkey of size " + size + " drawn");

}
// ...more methods
}

// ....more classes implementing animal interface
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top