我正在尝试做什么创建汽车,为创建的每辆汽车分配一个名称。
以下是我所做的:
//.....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
命令,尝试从地图上获取汽车。如果未找到,请创建汽车并添加到地图。
如果它是一个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();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)