Question

Task In this challenge you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task
Specification Challenge.parseHtml Colo r(colo r) Takes a String that represents a color and returns the parsed color as a map
import java.util . Map; public class HtmlColorParser private final Map<String, String> presetColors ; public HtmlColorParser
Task In this challenge you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task is to implement a function which takes a color as a string and returns the parsed color as a map (see Examples). Input represents one of the following: color The input string 1.6-digit hexadecimal "#RRGGBB" - Each pair of digits represents a value of the channel in hexadecimal: 00 to FF 2.3-digit hexadecimal "#RGB" - Each digit represents a value 0 to F which translates to 2- digit hexadecimal: 0>00, 1 11, 2->22, and so on. 3. Preset color name You have to use the predefined map PRESET_COLORS (Ruby, Python, JavaScript), presetColorsHaskell), or preset- colors (Clojure). The keys are the names of preset colors in lower- case and the values are the corresponding colors in 6-digit hexadecimal (same as 1. "#RRGGBB" ).
Specification Challenge.parseHtml Colo r(colo r) Takes a String that represents a color and returns the parsed color as a map. Parameters color: String-A color represented by color name, 3- digit hexadecimal or 6-digit hexadecimal Return Value HashMap-Aset of numerical RGB values Examples color Return Value "#80FFA0" {"r":128,"g":255," b":160) "# 3B7" {"r":51,"g":187,"b ":119) "LimeGreen" ("r":50,"g":205 , "b ":50)
import java.util . Map; public class HtmlColorParser private final Map presetColors ; public HtmlColorParser ( Map presetColors) presetColors; this.presetColors } public RGB parse (String color) { return new RGB (0, 128, 255); }
0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.HashMap;
import java.util.Map;

public class HtmlColorParser {
    private final Map<String, String> presetColors;

    //Initializing preset color in map
    public HtmlColorParser(Map<String, String> presetColors) {
        this.presetColors = presetColors;
    }

    //parsing color string
    public RGB parse(String colorString) throws Exception {
        //when hex code used
        if (colorString.startsWith("#")) {
            String colorValue = colorString.substring(1);
            String reformattedValue = reformatColorValue(colorValue);
            return getRgb(reformattedValue);
        }
        //when preset colors used
        if (presetColors.containsKey(colorString.toLowerCase())) {
            return getRgb(this.presetColors.get(colorString.toLowerCase()).substring(1));
        }

        throw new Exception("Invalid color");
    }


    private String reformatColorValue(String colorValue) {
        if (colorValue.length() == 6) {
            return colorValue;
        }
        return getDoubleString(colorValue.substring(0, 1))
                + getDoubleString(colorValue.substring(1, 2))
                + getDoubleString(colorValue.substring(2, 3));
    }

    private String getDoubleString(String str) {
        return str + str;
    }


    //parsing logic
    private RGB getRgb(String colorString) {
        int red = Integer.parseInt(colorString.substring(0, 2), 16);
        int green = Integer.parseInt(colorString.substring(2, 4), 16);
        int blue = Integer.parseInt(colorString.substring(4, 6), 16);
        return new RGB(red, green, blue);
    }


    public static void main(String args[]) {
        Map<String, String> presetColor = new HashMap<>();
        presetColor.put("limegreen", "#32CD32");
        presetColor.put("green", "#008000");
        presetColor.put("blue", "#0000FF");
        presetColor.put("red", "#FF0000");
        presetColor.put("black", "#000000");
        presetColor.put("white", "#FFFFFF");

        try {
            HtmlColorParser htmlColorParser = new HtmlColorParser(presetColor);
            System.out.println("#80FFA0: " + htmlColorParser.parse("#80FFA0"));
            System.out.println("#3B7: " + htmlColorParser.parse("#3B7"));
            System.out.println("LimeGreen: " + htmlColorParser.parse("LimeGreen"));
            System.out.println("Blue: " + htmlColorParser.parse("Blue"));
            System.out.println("Red: " + htmlColorParser.parse("red"));
        } catch (Exception e) {
            System.out.println("One of the color is invalid");
        }
    }
}

class RGB {
    private final int r;
    private final int b;
    private final int g;


    RGB(int r, int b, int g) {
        this.r = r;
        this.b = b;
        this.g = g;
    }

    @Override
    public String toString() {
        return "{" +
                "r:" + r +
                ", b:" + b +
                ", g:" + g +
                '}';
    }
}
/Library/Java/JavaVirtualMachines/openjdk-12.0.1.jdk/Contents/H #80FFA0: {r:128, b:255, g:160} #3B7: {r:51, b:187, g:119} Lim
Add a comment
Know the answer?
Add Answer to:
Task In this challenge you parse RGB colors represented by strings. The formats are primarily used...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Task The task for this assignment is to have the following user-defined data type: struct rgb...

    Task The task for this assignment is to have the following user-defined data type: struct rgb { unsigned char red; unsigned char green; unsigned char blue; }; be able to be: read in from a stream (e.g., std::cin), i.e., write: std::istream& operator >>(std::istream& is, rgb& colour); (see below) written out to a stream (e.g., std::cout), i.e., write: std::ostream& operator <<(std::ostream& os, rgb const& colour); (see below) stored in a container, e.g., std::vector<rgb>, std::array<rgb,16>; (see below) processed via algorithms (and other...

  • This task involves constructing a Java program that supports interaction via a graphical user interface.The object...

    This task involves constructing a Java program that supports interaction via a graphical user interface.The object is to implement a Scrabble graphical game. The basis for the game is quite simple. Presented with a 6x6 grid of Scrabble tiles, the challenge is for the player(s) to form as many high scoring words as possible.  Words may only be formed from sequences of adjacent tiles.  Two tiles are adjacent if their edges or corners meet.  A tile may...

  • Mountain Paths (Part 1) Objectives 2d arrays Store Use Nested Loops Parallel data structures (i.e...

    Mountain Paths (Part 1) in C++ Objectives 2d arrays Store Use Nested Loops Parallel data structures (i.e. parallel arrays … called multiple arrays in the zyBook) Transform data Read from files Write to files structs Code Requirements Start with this code: mtnpathstart.zip Do not modify the function signatures provided. Do not #include or #include Program Flow Read the data into a 2D array Find min and max elevation to correspond to darkest and brightest color, respectively Compute the shade of...

  • Mountain Paths (Part 1) in C++ Objectives 2d arrays Store Use Nested Loops Parallel data structures...

    Mountain Paths (Part 1) in C++ Objectives 2d arrays Store Use Nested Loops Parallel data structures (i.e. parallel arrays … called multiple arrays in the zyBook) Transform data Read from files Write to files structs Code Requirements Start with this code: mtnpathstart.zip Do not modify the function signatures provided. Do not #include or #include Program Flow Read the data into a 2D array Find min and max elevation to correspond to darkest and brightest color, respectively Compute the shade of...

  • from PIL import Image import random # NOTE: Feel free to add in any constant values...

    from PIL import Image import random # NOTE: Feel free to add in any constant values you find useful to use BLACK = (0, 0, 0) WHITE = (255, 255, 255) # NOTE: Feel free to add in any helper functions to organize your code but # do NOT rename any existing functions (or else, autograder # won't be able to find them!!) # NOTE: The following function is already completed for you as an example # You can use...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

  • programming language: C++ *Include Line Documenatations* Overview For this assignment, write a program that will simulate...

    programming language: C++ *Include Line Documenatations* Overview For this assignment, write a program that will simulate a game of Roulette. Roulette is a casino game of chance where a player may choose to place bets on either a single number, the colors red or black, or whether a number is even or odd. (Note: bets may also be placed on a range of numbers, but we will not cover that situation in this program.) A winning number and color is...

  • Problem Statement: A company intends to offer various versions of roulette game and it wants you...

    Problem Statement: A company intends to offer various versions of roulette game and it wants you to develop a customized object-oriented software solution. This company plans to offer one version 100A now (similar to the simple version in project 2 so refer to it for basic requirements, but it allows multiple players and multiple games) and it is planning to add several more versions in the future. Each game has a minimum and maximum bet and it shall be able...

  • Your teacher is going to give a test where each student is to answer one question. None of the neighboring students should have the same question. How many questions are needed? Graph Coloring Algorit...

    Your teacher is going to give a test where each student is to answer one question. None of the neighboring students should have the same question. How many questions are needed? Graph Coloring Algorithm is used to solve this type of problems. It does not guarantee to use the minimum number of questions, but it guarantees an upper bound on the number of questions. The algorithm never uses more than d+1 questions where d is the maximum degree of vertices...

  • Overview: You will be writing classes that implement a playlist simulation for a music streaming app.The...

    Overview: You will be writing classes that implement a playlist simulation for a music streaming app.The Playlist class will contain a dynamic array of Song objects, and the Song class contains several pieces of information about a song. You will need to: 1) Finish the writing of two classes: Song and Playlist. The full header file for the Song class has been provided in a file called Song.h. 2) Write a main program (filename menu.cpp) that creates a single Playlist...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT