Eagle Two
Eagle Two

Reputation: 31

Key to Value associations

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

Below is what I have done:

//.....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.......

The problem I am facing:

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.

Upvotes: 3

Views: 123

Answers (2)

Eran
Eran

Reputation: 393856

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

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180388

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.

Upvotes: 1

Related Questions