价值联想的关键

我要做的是创建汽车,为每辆创建的汽车分配一个名称。

以下是我所做的:

//.....codes public class Cars { Map vehicleNames = new HashMap (); 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 )和对现有车辆执行操作的命令( car name carname action )。

  • 如果是car name命令,请尝试从地图中获取汽车。 如果找不到,请创建汽车并添加到地图。

  • 如果是carname action命令,请尝试从地图中获取汽车。 如果找不到,则显示错误消息。 如果找到,请对其执行操作。

这是一种使逻辑工作的建议方法:

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

您假设汽车的名称是第二条指令:

  boolean blnExists =carNames.containsKey(instructions[1]); 

但这只适用于’汽车’命令。 对于其他命令,汽车的名称是第一条指令。

你这里也有一个问题:

  if (instructions[1].equals("build")){ car.makeVisible(); } 

可变car没有引用具有给定名称的汽车(您只检查了它的存在 – 您实际上还没有检索它),因此输出将不对应于该汽车。

你的代码还有其他一些奇怪的东西,但我认为在快速阅读中没有任何错误。