Key to Value associations

前端 未结 2 819
时光说笑
时光说笑 2021-01-03 09:12

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

Below is what I have done:

//.....codes
         


        
相关标签:
2条回答
  • 2021-01-03 09:27
    • 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.

    • 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();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 09:37

    You are assuming that the name of the car is the second instruction:

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

    but that is correct only for a 'car' command. For the other commands, the name of the car is the first instruction.

    You also have an issue here:

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

    Variable car does not reference the car with the given name (you only checked its existence -- you didn't actually retrieve it yet), so the output will not correspond to that car.

    There are some other strange things about your code, but nothing that I recognize as erroneous on a quick read-through.

    0 讨论(0)
提交回复
热议问题