The key to value associations

I am trying to do by creating cars by assigning a name to each car created.

Below is what I did:

//.....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, the car names are stored in the HashMap as I wanted. But the machines created do not seem to be associated with their respective names.

+3


source to share


2 answers


  • 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 command car name

    , try removing the car from the map. If not found, create a car and add it to the map.

  • If it's a command carname action

    , try removing the car from the map. If not found, display an error message. If it is found, take 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();
        }
    }
}

      

+2


source


You are assuming the car name is the second statement:

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

      

but this is only true for the "car" command. For other commands, the vehicle name is the first instruction.

You also have a problem:



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

      

The variable car

does not refer to the car with the given name (you only checked for its existence - you have not checked it out yet), so the output will not match that car.

There are other weird things about your code as well, but nothing that I believe is a mistake on a quick read.

+1


source







All Articles