将实例替换为变量



如何让用户输入以让用户选择哪个厨师必须准备食物?

在 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???*
*/
}
}

如果您希望用户选择厨师,则需要从 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.
}
}

最新更新