价值联想的关键 [英] Key to Value associations

查看:96
本文介绍了价值联想的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是是创建汽车,为每辆创建的汽车指定一个名称。

What I am trying to do is create cars, assign a name to each car created.

以下是我的工作:

//.....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中。但是创建的汽车似乎与他们各自的名字无关。

The program compiles and works fine, car names are being stored in the HashMap as I wanted. But the cars created don't seem to be associated to their respective names.

推荐答案


  • 首先,您要区分创建新车的命令(汽车名称)和对现有汽车执行操作的命令( carname action )。

    • First, you want to distinguish between a command to create a new car (car name) and a command to perform an action on an existing car (carname action).

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

      If it's a car name command, try to fetch the car from the map. If it's not found, create the car and add to map.

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

      If it's a carname action command, try to fetch the car from the map. If it's not found, display an error message. If it's found, perform the action on it.

      这是建议的逻辑工作方式:

      Here's a suggested way to make your logic work :

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

      这篇关于价值联想的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆