我想做的是创造汽车,为每辆创造的汽车分配一个名字。
以下是我所做的:
//.....codes
public class Cars {
Map<String, Vehicle> vehicleNames = new HashMap <String, Vehicle>();
Car car = new Car();
private void execute(String[] instructions)
{
boolean blnExists =vehicleNames.containsKey(instructions[1]);
System.out.println("Exists? : " + blnExists);
if (blnExists){
if (instructions[1].equals("build")){
car.makeVisible();
}
}
else {
System.out.println("Does not exist yet!");
}
//more codes.......
我面临的问题:
程序编译并运行良好,汽车名称按照我的需要存储在 HashMap 中。但是创建的汽车似乎与它们各自的名称无关。
最佳答案
首先,您要区分创建新汽车的命令 (
car name
) 和对现有汽车执行操作的命令 (carname action
)。如果它是
car name
命令,尝试从 map 中获取汽车。如果未找到,则创建汽车并添加到 map 。如果它是
carname action
命令,尝试从 map 中获取汽车。如果未找到,则显示一条错误消息。如果找到,则对其执行操作。
这里有一个让你的逻辑工作的建议方法:
if (instructions[0].equals("car")) {
Vehicle v = vehicleNames.get(instructions[1]);
if (v == null) {
// put here the code that adds a vehicle to the map
} else {
// display a message that the vehicle already exists
}
} else {
Vehicle v = vehicleNames.get(instructions[0]);
if (v == null) {
// display a message that car was not found
} else {
// perform an action on existing car. For example :
if (instructions[1].equals("build") {
v.makeVisible();
}
}
}
关于java - 值(value)协会的关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27824858/