用变量替换实例

replace an instance by a variable

我怎样才能让用户输入 select 哪个厨师必须准备食物?

在LINE33中deliverer1.delivered(cook1, customer);cook1是一个固定的实例,但最好是一种变量来表示cook1cook2

class DamascusShoarma {

   static int Cooksnumber;
   static int Deliverersnumber;

   @SuppressWarnings("unused")
   public static void main(String[] args) {
      Cook cook1 = new Cook("Jan de Vries", "Slagersmes 1", "1212-IS",
            "Allahmelo", 123456);
      Cook cook2 =
            new Cook("Sinbad", "Kameelbult 2", "2323-IS", "Halal-lem", 654321);
      Deliverer deliverer1 = new Deliverer("Ali Baba", "Helmgras 11", "3434-JH",
            "Ji-Hattem", 456789);
      Deliverer deliverer2 = new Deliverer("Muammar", "Zadeldreef 22",
            "4545-JH", "Moskemenade", 987654);
      Customer customer = new Customer("Piet Hein", "Maagdenburglaan 5",
            "5656-KL", "Darmstadt");
      cooksnumber = Cook.Cooksnumber;

      deliverersnumber = Deliverer.Deliverersnumber;

      deliverer1.delivered(cook1,
            customer); /*
                        * Line 33 the line that matters to my question. cook1 is
                        * a fixed instance. How can this be a kind of variable
                        * so that it could also represent cook2 if wished???*
                        */
   }
}

如果您希望用户 select 厨师,您需要从 UI 中获取或使用参数。然后你可以使用@luk2302 的建议来设置变量。例如(仅示例代码)使用第一个参数作为厨师的名字:

class DamascusShoarma {

    static int Cooksnumber;
    static int Deliverersnumber;

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        // ... Set delivers, customers etc...

        Cook cook1 = new Cook("Jan de Vries", "Slagersmes 1", "1212-IS",
            "Allahmelo", 123456);
        Cook cook2 =
            new Cook("Sinbad", "Kameelbult 2", "2323-IS", "Halal-lem", 654321);

        Hashmap<String, Cook> cooks = new Hashmap()<String, Cook>;

        cooks.put(cook1.name, cook1);
        cooks.put(cook2.name, cook2);

        Cook cook = null;
        if (args.length > 1 && args.args[1] != null)
        {
            cook = cooks.get(args[1]);  // This is the answer to the question
        }
        // TODO Error check in case cook == null

        cooksnumber = cook.Cooksnumber;  // Used here

        // TODO - do something similar to cooks to select the deliverer
        // and customer
        deliverersnumber = Deliverer.Deliverersnumber;

        deliverer.delivered(cook, customer);  // And here.

    }
}