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

+++++++++++++++++++Java+++++++++++++++++++++++++++ make three methods that are s

ID: 3586809 • Letter: #

Question

+++++++++++++++++++Java+++++++++++++++++++++++++++

make three methods that are specified in the GraphingMethods class also make helper method which can help three method.

Rightnow method contains hard cording change this to flexible cord. ( watch for the comment)

public class GraphingMethods
{
/**
* Constant used to request a max operation
*/
public final static int MAX = 0;

/**
* Constant used to request a min operation
*/
public final static int MIN = 1;

/**
* Constant used to request a sum operation
*/
public final static int SUM = 2;

/**
* Constant used to request an average operation
*/
public final static int AVG = 3;

/**
* The dataSource must consist of one or more lines. If there is not at least one line, the method throws an
* IllegalArgumentException whose message explains what is wrong.
*
* Each line must consist of some text (a key), followed by a tab character, followed by a double literal (a value),
* followed by a newline.
*
* If any lines are encountered that don't meet this criteria, the method throws an IllegalArgumentException whose
* message explains what is wrong.
*
* Otherwise, the map returned by the method (here called categoryMap) must have all of these properties:
*
* (1) The set of keys contained by categoryMap must be the same as the set of keys that occur in the Scanner
*
* (2) The list valueMap.get(key) must contain exactly the same numbers that appear as values on lines in the
* Scanner that begin with key. The values must occur in the list in the same order as they appear in the Scanner.
*
* For example, if the Scanner contains
*
*


*
* (where the spaces in each line are intended to be a single tab), then this map should be returned:
*
*


*/
public static TreeMap> readTable (Scanner dataSource)
{
// This implementation ignores its parameters and returns the map described in the Javadoc.
TreeMap> map = new TreeMap<>();

ArrayList azList = new ArrayList<>();
azList.add(21.0);
map.put("Arizona", azList);

ArrayList caList = new ArrayList<>();
caList.add(14.0);
caList.add(7.0);
caList.add(6.0);
caList.add(1.0);
map.put("California", caList);

ArrayList nvList = new ArrayList<>();
nvList.add(3.0);
nvList.add(11.0);
map.put("Nevada", nvList);

ArrayList utList = new ArrayList<>();
utList.add(10.0);
utList.add(2.0);
utList.add(2.0);
map.put("Utah", utList);

return map;
}

/**
* If categoryMap is of size zero, throws an IllegalArgumentException whose message explains what is wrong.
*
* Else if any of the values in the category map is an empty set, throws an IllegalArgumentException whose message
* explains what is wrong.
*
* Else if any of the numbers in the categoryMap is not positive, throws an IllegalAgumentException whose message
* explains what is wrong.
*
* Else if operation is anything other than SUM, AVG, MAX, or MIN, throws an IllegalArgumentException whose message
* explains what is wrong.
*
* Else, returns a TreeMap (here called summaryMap) such that:
*
* (1) The sets of keys contained by categoryMap and summaryMap are the same
*
* (2) For all keys, summaryMap.get(key) is the result of combining the numbers contained in the set
* categoryMap.get(key) using the specified operation. If the operation is MAX, "combining" means finding the
* largest of the numbers. If the operation is MIN, "combining" means finding the smallest of the numbers. If the
* operation is SUM, combining means summing the numbers. If the operation is AVG, combining means averaging the
* numbers.
*
* For example, suppose the categoryMap maps like this:
*
*


*
* and the operation is SUM. The map that is returned must map like this:
*
*


*/
public static TreeMap prepareGraph (TreeMap> categoryMap, int operation)
{
// This implementation ignores its parameters and returns the map described in the Javadoc.
TreeMap summaryMap = new TreeMap<>();
summaryMap.put("Arizona", 21.0);
summaryMap.put("Arizona", 28.0);
summaryMap.put("Arizona", 14.0);
summaryMap.put("Arizona", 21.0);
return summaryMap;
}

/**
* If colorMap is empty, throws an IllegalArgumentException.
*
* If there is a key in colorMap that does not occur in summaryMap, throws an IllegalArgumentException whose message
* explains what is wrong.
*
* If any of the numbers in the summaryMap is non-positive, throws an IllegalArgumentException whose message
* explains what is wrong.
*
* Otherwise, displays on g the subset of the data contained in summaryMap that has a key that appears in colorMap
* with either a pie chart (if usePieChart is true) or a bar graph (otherwise), using the colors in colorMap.
*
* Let SUM be the sum of all the values in summaryMap whose keys also appear in colorMap, let KEY be a key in
* colorMap, let VALUE be the value to which KEY maps in summaryMap, and let COLOR be the color to which KEY maps in
* colorMap. The area of KEY's slice (in a pie chart) and the length of KEY's bar (in a bar graph) must be
* proportional to VALUE/SUM. The slice/bar should be labeled with both KEY and VALUE, and it should be colored with
* COLOR.
*
* For example, suppose summaryMap has this mapping:
*
*


*
* and colorMap has this mapping:
*
*


*
* Since Arizona does not appear as a key in colorMap, Arizona's entry in summaryMap is ignored.
*
* In a pie chart Utah and Nevada should each have a quarter of the pie and California should have half. In a bar
* graph, California's line should be twice as long as Utah's and Nevada's. Utah's slice/bar should be red, Nevada's
* blue, and California's green.
*
* The method should display the pie chart or bar graph by drawing on the g parameter. The example code below draws
* both a pie chart and a bar graph for the situation described above.
*/
public static void drawGraph (Graphics g, TreeMap summaryMap, TreeMap colorMap,
boolean usePieChart)
{
// This implementation ignores its parameters (except for usePieChart) and draws a pie chart or a bar graph
// for the data described in the Javadoc.

final int TOP = 10; // Offset of graph from top edge
final int LEFT = 10; // Offset of graph from left edge
final int DIAM = 300; // Diameter of pie chart
final int WIDTH = 10; // Width of bar in bar chart

// Draw a pie chart if requested
if (usePieChart)
{
// Draw the entire circle California's color, plus its label
g.setColor(Color.GREEN);
g.fillArc(LEFT, TOP, DIAM, DIAM, 0, 360);
g.fillRect(LEFT + DIAM + 2 * WIDTH, TOP, WIDTH, WIDTH);
g.setColor(Color.black);
g.drawString("California 28.00", LEFT + DIAM + 4 * WIDTH, TOP + WIDTH);

// Draw Nevada's quarter wedge, plus its label
g.setColor(Color.BLUE);
g.fillArc(LEFT, TOP, DIAM, DIAM, 180, 90);
g.fillRect(LEFT + DIAM + 2 * WIDTH, TOP + 2 * WIDTH, WIDTH, WIDTH);
g.setColor(Color.black);
g.drawString("Nevada 14.00", LEFT + DIAM + 4 * WIDTH, TOP + 3 * WIDTH);

// Draw Utah's half wedge, plus its label
g.setColor(Color.RED);
g.fillArc(LEFT, TOP, DIAM, DIAM, 270, 90);
g.fillRect(LEFT + DIAM + 2 * WIDTH, TOP + 4 * WIDTH, WIDTH, WIDTH);
g.setColor(Color.black);
g.drawString("Utah 14.00", LEFT + DIAM + 4 * WIDTH, TOP + 5 * WIDTH);
}

// Draw a bar chart if requested
else
{
// Draw California's bar, plus its label
g.setColor(Color.GREEN);
g.fillRect(LEFT + DIAM - DIAM / 2, TOP, DIAM / 2, 2 * WIDTH);
g.setColor(Color.black);
g.drawString("California 28.00", LEFT + DIAM + 2 * WIDTH, TOP + WIDTH + WIDTH / 2);

// Draw Nevada's bar, plus its label
g.setColor(Color.BLUE);
g.fillRect(LEFT + DIAM - DIAM / 4, TOP + 3 * WIDTH, DIAM / 4, 2 * WIDTH);
g.setColor(Color.black);
g.drawString("Nevada 14.00", LEFT + DIAM + 2 * WIDTH, TOP + 4 * WIDTH + WIDTH / 2);

// Draw Utah's bar, plus its label
g.setColor(Color.RED);
g.fillRect(LEFT + DIAM - DIAM / 4, TOP + 6 * WIDTH, DIAM / 4, 2 * WIDTH);
g.setColor(Color.black);
g.drawString("Utah 14.00", LEFT + DIAM + 2 * WIDTH, TOP + 7 * WIDTH + WIDTH / 2);
}
}
}

Explanation / Answer


import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeMap;


public class GraphingMethods
{
    /**
     * Constant used to request a max operation
     */
    public final static int MAX = 0;

    /**
     * Constant used to request a min operation
     */
    public final static int MIN = 1;

    /**
     * Constant used to request a sum operation
     */
    public final static int SUM = 2;

    /**
     * Constant used to request an average operation
     */
    public final static int AVG = 3;

    /**
     * Parses a properly-formatted data source and returns a TreeMap of the data within. For example, data set
     *
     * <pre>
     * Alabama 4
     * Alaska   4
     * Alaska   4
     * Arizona 10
     * Arizona 22
     * Arkansas 8
     * California   9
     * California   9
     * California   18
     * </pre>
     *
     * will be parsed and TreeMap
     *
     * <pre>
     * Alabama, {4}
     * Alaska, {4, 4}
     * Arizona, {10, 22}
     * Arizona, {8}
     * California   {9, 9, 18}
     * </pre>
     *
     * will be returned.
     *
     *
     */
    public static TreeMap<String, ArrayList<Double>> readTable (Scanner dataSource)
    {
        // Create a TreeMap to store the result
        TreeMap<String, ArrayList<Double>> map = new TreeMap<>();

        // Track which line is currently being analyzed
        int lineTracker = 0;
      
        if (!(dataSource.hasNextLine())) { // If there aren't any lines in the data,
          
            throw new IllegalArgumentException("Source must contain data.");
          
        }
      
        // While the datasource has another line,
        while (dataSource.hasNextLine())
        {

            lineTracker++;
            String key = "";
            Double value = 0.0;
          
            /*
             * Uses as a divider to split each line into a key and a data point.
             * Example, a line that says
             *
             * Nevada 20
             *
             * will be split into
             *
             * {"Nevada", "20"}
             *
             * The program then parses the second entry as a double.
             */
            try
            {
                String[] entry = dataSource.nextLine().split(" ");
                key = entry[0];
                value = Double.parseDouble(entry[1]);
            }
            catch (NumberFormatException e) // If the value isn't able to be parsed to a double,
            {
                throw new IllegalArgumentException("Entry " + lineTracker + " is improperly formatted.");
            }
            catch (ArrayIndexOutOfBoundsException e) // If the line isn't split into at least two pieces
            {
                throw new IllegalArgumentException("Entry " + lineTracker + " is improperly formatted.");
            }

            if (!(map.containsKey(key))) // If the map doesn't already have the key,
            {
                map.put(key, new ArrayList<Double>()); // Create an entry with that key and a new list to put values into.
            }

            map.get(key).add(value); // Add the value to the key's table.

        }

        return map;
    }

    /**
     * Processes the data within a categoryMap by determining each key's
     * - minimum value,
     * - maximum value,
     * - summed value,
     * - averaged value,
     *
     * and returning the result as a summaryMap.
     *
     * @param categoryMap, generated by readTable
     * @param an operation listed under GraphingMethods' int variables.
     *
     * @throws IllegalArgumentException if categoryMap is empty
     * @throws IllegalArgumentException if the requested operation doesn't exist
     * @throws IllegalArgumentException if any key's categoryMap table is empty
     * @throws IllegalArgumentException if any key's table value is 0 or negative.
     *
     * @return a summaryMap with the data processed from the categoryMap assigned to the keys.
     */
    public static TreeMap<String, Double> prepareGraph (TreeMap<String, ArrayList<Double>> categoryMap, int operation)
          
    {

        // Check for exceptions.
        // Ironically, this if-else block is larger than the rest of the method.
        if (categoryMap.size() <= 0)
        {
            throw new IllegalArgumentException("Category map size must be greater than 0");
        }
        else if (operation < 0 || operation > 3)
        {
            throw new IllegalArgumentException("Operation " + operation + " does not exist.");
        }
        else
        {
            for (String key : categoryMap.keySet())
            {
                if (categoryMap.get(key).size() <= 0)
                {
                    throw new IllegalArgumentException("Category Map contains empty key: " + key);
                }

                for (double value : categoryMap.get(key))
                {
                    if (value < 0) // I know it's bad form to do conditionals with doubles, but this should be okay(?)
                    {
                        throw new IllegalArgumentException("Key " + key + " contains negative value " + value);
                    }

                }

            }

        }

        TreeMap<String, Double> summaryMap = new TreeMap<>();

        if (operation == GraphingMethods.SUM)
        {
            summaryMap = sumCategoryMap(categoryMap);
        }
        else if (operation == GraphingMethods.AVG)
        {
            summaryMap = avgCategoryMap(categoryMap);
        }
        else if (operation == GraphingMethods.MIN)
        {
            summaryMap = minCategoryMap(categoryMap);
        }
        else if (operation == GraphingMethods.MAX)
        {
            summaryMap = maxCategoryMap(categoryMap);
        }

        return summaryMap;

    }

    /**
     * Sums up all of the values within a category for a valid CategoryMap.
     *
     * For example, the categoryMap
     *
     * <pre>
     * Arizona    {21
     * California {14, 7, 6, 1}
     * Nevada     {3, 11}
     * Utah       {10, 2, 2}
     * </pre>
     *
     * would be returned as summaryMap:
     *
     * <pre>
     * Arizona    21
     * California 28
     * Nevada     14
     * Utah       14
     * </pre>
     *
     * @param categoryMap
     * @return categoryMap with table of values summed to one value.
     */
    private static TreeMap<String, Double> sumCategoryMap (TreeMap<String, ArrayList<Double>> categoryMap)
    {
        TreeMap<String, Double> result = new TreeMap<>();

        for (String key : categoryMap.keySet())
        {
            double keySum = 0.0;

            for (double value : categoryMap.get(key))
            {
                keySum += value;
            }
            result.put(key, keySum);
        }
        return result;
    }

    /**
     * Averages all of the values within a category for a valid CategoryMap.
     *
     * For example, suppose the categoryMap maps like this:
     *
     * <pre>
     * Arizona    {21}
     * California {14, 7, 6, 1}
     * Nevada     {3, 11}
     * Utah       {10, 2, 2}
     * </pre>
     *
     * The map that is returned is:
     *
     * <pre>
     * Arizona    21
     * California 7
     * Nevada     7
     * Utah       4.666(...)
     * </pre>
     *
     * @param categoryMap
     * @return categoryMap with table of values averaged as one value.
     */
    private static TreeMap<String, Double> avgCategoryMap (TreeMap<String, ArrayList<Double>> categoryMap)
    {
        TreeMap<String, Double> result = new TreeMap<>();

        for (String key : categoryMap.keySet())
        {
            double keySum = 0.0;

            for (double value : categoryMap.get(key))
            {
                keySum += value;
            }
            double keyAvg = keySum / categoryMap.get(key).size();

            result.put(key, keyAvg);
        }
        return result;
    }

    /**
     * Finds the minimum value within a category for a valid CategoryMap.
     *
     * For example, suppose the categoryMap maps like this:
     *
     * <pre>
     * Arizona    {21}
     * California {14, 7, 6, 1}
     * Nevada     {3, 11}
     * Utah       {10, 2, 2}
     * </pre>
     *
     * The map that is returned is:
     *
     * <pre>
     * Arizona    21
     * California 1
     * Nevada     3
     * Utah       2
     * </pre>
     *
     * @param categoryMap
     * @return categoryMap with only minimum values.
     */
    private static TreeMap<String, Double> minCategoryMap (TreeMap<String, ArrayList<Double>> categoryMap)
    {
        TreeMap<String, Double> result = new TreeMap<>();

        for (String key : categoryMap.keySet())
        {
            double lowestValue = categoryMap.get(key).get(0); // ASSUMPTION: Empty arrays have been filtered out by this
                                                              // point.

            for (double value : categoryMap.get(key))
            {
                if (value < lowestValue)
                {
                    lowestValue = value;
                }
            }
            result.put(key, lowestValue);
        }
        return result;
    }

    /**
     * Finds the maximum value within a category for a valid CategoryMap.
     *
     * For example, suppose the categoryMap maps like this:
     *
     * <pre>
     * Arizona    {21}
     * California {14, 7, 6, 1}
     * Nevada     {3, 11}
     * Utah       {10, 2, 2}
     * </pre>
     *
     * The map that is returned is:
     *
     * <pre>
     * Arizona    21
     * California 14
     * Nevada     11
     * Utah       10
     * </pre>
     *
     * @param categoryMap
     * @return categoryMap with only maximum values.
     */
    private static TreeMap<String, Double> maxCategoryMap (TreeMap<String, ArrayList<Double>> categoryMap)
    {

        TreeMap<String, Double> result = new TreeMap<>();

        for (String key : categoryMap.keySet())
        {
            double greatestValue = categoryMap.get(key).get(0); // ASSUMPTION: Empty arrays have been filtered out by
                                                                // this point.
            for (double value : categoryMap.get(key))
            {
                if (value > greatestValue)
                {
                    greatestValue = value;
                }
            }
            result.put(key, greatestValue);
        }

        return result;

    }

    /**

     */
    public static void drawGraph (Graphics g, TreeMap<String, Double> summaryMap, TreeMap<String, Color> colorMap,
            boolean usePieChart)
    {

        final int TOP = 10;        // Offset of graph from top edge
        final int LEFT = 10;       // Offset of graph from left edge
        final int DIAM = 300;      // Diameter of pie chart
        final int WIDTH = 10;      // Width of bar in bar chart

        // Remove any keys that do not have a color assigned to them.
        Object[] keys = summaryMap.keySet().toArray(); // FUN FACT: If you try to remove something from the thing you're
                                                       // iterating over, it crashes.
        for (Object key : keys)
        {
            if (!(colorMap.containsKey(key)))
            {
                // System.out.println(key + " will be removed.");
                summaryMap.remove(key);

            }
        }

        // Generate percentage map.
        TreeMap<String, Double> percentageMap = assignSummaryPercentages(summaryMap);

        // Draw a pie chart if requested
        if (usePieChart)
        {
            // Start by drawing the first arc as a full circle, then draw smaller arcs over one another.
            int finalDegree = 360;
            int elementAdded = 0;

            for (String key : summaryMap.keySet())
            {

                g.setColor(colorMap.get(key));

                g.fillArc(LEFT, TOP, DIAM, DIAM, 0, finalDegree);
                finalDegree -= (int) (360.0 * percentageMap.get(key));
                // System.out.print("Final degree set to ");
                // System.out.println(finalDegree);

                g.fillRect(LEFT + DIAM + 2 * WIDTH, TOP + (WIDTH * 2) * (elementAdded), WIDTH, WIDTH);
                g.setColor(Color.black);
                g.drawString(key + ' ' + String.format("%4.2f", summaryMap.get(key)), LEFT + DIAM + 4 * WIDTH,
                        TOP + WIDTH + (WIDTH * 2) * (elementAdded));

                elementAdded++;

            }
        }

        // Draw a bar chart if requested
        else
        {

            int elementAdded = 0;

            for (String key : summaryMap.keySet())
            {
                int barLength = (int) (DIAM * percentageMap.get(key));

                g.setColor(colorMap.get(key));

                g.fillRect(LEFT + DIAM - barLength, TOP + elementAdded * 10 * WIDTH / 3, barLength, WIDTH * 2);

                g.setColor(Color.black);
                g.drawString(key + ' ' + String.format("%4.2f", summaryMap.get(key)), 2 * LEFT + DIAM,
                        5 * TOP / 2 + elementAdded * 10 * WIDTH / 3);

                elementAdded++;
            }
            ;
        }
    }

    private static TreeMap<String, Double> assignSummaryPercentages (TreeMap<String, Double> summaryMap)
    {

        TreeMap<String, Double> result = new TreeMap<>();

        // Get the sum of all the Summary Map values.
        double sum = 0.0;
        for (String key : summaryMap.keySet())
        {

            sum += summaryMap.get(key);

        }

        // Get the percentage of each key's value relative to the sum and put it in the result.
        for (String key : summaryMap.keySet())
        {

            result.put(key, summaryMap.get(key) / sum);

        }

        return result;

    }
}