Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java program that uses collections API The user should assign a name to each col

ID: 3569826 • Letter: J

Question

Java program that uses collections API

The user should assign a name to each color, and a unique hex value (example 0000FF blue)

User input can be done in a GUI

If the user enters a name for a color that already has that name, then the user should be reprompted. This needs to be applied to hex value too.

Additionally, a GUI should be included that displays the color names and hexadecimal values.

Each name/value pair should be selectable via a radio button or other mechanism.

When a color is selected, an area of the GUI should change to that color (the area is up to you, as long as it's visible).

This is what I have but I am confused by implementation of hashmap. Can someone help me understand how to use it correctly in my program?

Explanation / Answer

Here are the three APIs of HashMap that helps you..

1. boolean containsKey(Object key)

2. boolean containsValue(Object value)

3. boolean put(Object key, Object value)

All you need to do is..

Assuming 'color' as key and 'hexvalue' as value..

1. Put key and corresponding value into the map if and only if the key is not in the keys of the map and value is not in the values of the map.

2. If the you are successful with step 1 then you have nothing to prompt to the user. Otherwise, you will.

Note: Assuming that color and hexvalue are WrapperClasses of Primitive Data Types in Java. Otherwise, you need to override hashcode() and equals() API for your UserDefined Data Types.

Below is the Sample Code Snippet in Java..

import java.util.HashMap;

public class Test {
private HashMap<String, String> colorAndHexValue = new HashMap<String, String>();

   public boolean put(String color, String hexValue) {
       if (!colorAndHexValue.containsKey(color)) {
           if (!colorAndHexValue.containsValue(hexValue)) {
               colorAndHexValue.put(color, hexValue);
               return true;
           }
       }

       return false;
   }

   public static void main(String[] args) {
       Test test = new Test();
       System.out.println("IsAllowed: " + test.put("Black", "OOOOFF")); // Output: true
       System.out.println("IsAllowed: " + test.put("White", "1111FF")); // Output: true
       System.out.println("IsAllowed: " + test.put("Black", "1111FF")); // Output: false
       System.out.println("IsAllowed: " + test.put("White", "OOOOFF")); // Output: false
       System.out.println("IsAllowed: " + test.put("Black", "OOOOFF")); // Output: false
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote