Key to Value associations

前端 未结 2 837
时光说笑
时光说笑 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();
            }
        }
    }
    

提交回复
热议问题