Question

In: Computer Science

Package pacman.score Class ScoreBoard Object ScoreBoard public class ScoreBoard extends Object ScoreBoard contains previous scores and...

Package pacman.score

Class ScoreBoard

  • Object
    • ScoreBoard
  • public class ScoreBoard
    extends Object
    ScoreBoard contains previous scores and the current score of the PacmanGame. A score is a name and value that a valid name only contains the following characters:
    • A to Z
    • a to z
    • 0 to 9
    and must have a length greater than 0. The value is a integer that is equal to or greater than 0.

    Implement this for Assignment 1

    • Constructor Summary

      Constructors
      Constructor Description
      ScoreBoard()

      Creates a score board that has no entries and a current score of 0.

    • Method Summary

      All MethodsInstance MethodsConcrete Methods
      Modifier and Type Method Description
      List<String> getEntriesByName()

      Gets the stored entries ordered by Name in lexicographic order.

      List<String> getEntriesByScore()

      Gets the stored entries ordered by the score in descending order ( 9999 first then 9998 and so on ...) then in lexicographic order of the name if the scores match.

      int getScore()

      Get the current score.

      void increaseScore​(int additional)

      Increases the score if the given additional is greater than 0.

      void reset()

      Set the current score to 0.

      void setScore​(String name, int score)

      Sets the score for the given name if: name is not null name is a valid score name score is equal to or greater than zero. This should override any score stored for the given name if name and score are valid.

      void setScores​(Map<String,​Integer> scores)

      Sets a collection of scores if "scores" is not null, otherwise no scores are modified.

      • Methods inherited from class Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • ScoreBoard

        public ScoreBoard()

        Creates a score board that has no entries and a current score of 0.

        Implement this for Assignment 1

    • Method Detail

      • getEntriesByName

        public List<String> getEntriesByName()
        Gets the stored entries ordered by Name in lexicographic order. The format of the list should be:
        1. Score name with a single space afterwards
        2. A single colon
        3. A space then the value of the score with no leading zeros.
        Example:
             ScoreBoard board = new ScoreBoard();
             board.setScore("Fred", 100);
             board.setScore("fred", 20);
             board.setScore("Fred", 24);
        
             List<String> scores = board.getEntriesByName();
             System.out.println(scores);
        
             // this outputs:
             // [Fred : 24, fred : 20]
        
         

        Returns:

        List of scores formatted as "NAME : VALUE" in the order described above or an empty list if no entries are stored.

        Implement this for Assignment 1

      • getEntriesByScore

        public List<String> getEntriesByScore()
        Gets the stored entries ordered by the score in descending order ( 9999 first then 9998 and so on ...) then in lexicographic order of the name if the scores match. The format of the list should be:
        1. Score name with a single space afterwards
        2. A single colon
        3. A space then the value of the score with no leading zeros.
        Example:
             ScoreBoard board = new ScoreBoard();
             board.setScore("Alfie", 100);
             board.setScore("richard", 20);
             board.setScore("Alfie", 24);
             board.setScore("ben", 20);
        
             List<String> scores = board.getEntriesByScore();
             System.out.println(scores);
        
             // this outputs
             // [Alfie : 24, ben : 20, richard : 20]
         

        Returns:

        List of scores formatted as "NAME : VALUE" in the order described above or an empty list if no entries are stored.

        Implement this for Assignment 1

      • setScore

        public void setScore​(String name, int score)
        Sets the score for the given name if:
        • name is not null
        • name is a valid score name
        • score is equal to or greater than zero.
        This should override any score stored for the given name if name and score are valid.

        Parameters:

        name - of scorer.

        score - to set to the given name.

        Implement this for Assignment 1

      • setScores

        public void setScores​(Map<String,​Integer> scores)
        Sets a collection of scores if "scores" is not null, otherwise no scores are modified. For each score contained in the scores if:
        • name is not null
        • name is a valid score name
        • score is equal to or greater than zero.
        the score will be set and override any stored score for the given name, otherwise it will be skipped.

        Parameters:

        scores - to add.

        Implement this for Assignment 1

      • increaseScore

        public void increaseScore​(int additional)

        Increases the score if the given additional is greater than 0. No change to the current score if additional is less than or equal to 0.

        Parameters:

        additional - score to add.

        Implement this for Assignment 1

      • getScore

        public int getScore()

        Get the current score.

        Returns:

        the current score.

        Implement this for Assignment 1

      • reset

        public void reset()

        Set the current score to 0.

How to use treemap to solve this problem?

Solutions

Expert Solution

package packman.score;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Map.Entry.*;
import java.util.stream.Collectors;

public class ScoreBoard extends Object {

   HashMap<String, Integer> scoreboard = new HashMap<String, Integer>();

   int currentScore;

   public ScoreBoard() {

       this.currentScore = 0;

   }

   public List<String> getEntriesByName() {

       List<String> names = new ArrayList<String>(scoreboard.keySet());
       Collections.sort(names);

       List<String> result = new ArrayList<>();

       for (String str : names) {
           result.add(str + " : " + scoreboard.get(str));
       }
       return result;

   }

   public List<String> getEntriesByScore() {
      
      
       //Using java8 feature
       HashMap<String, Integer> sortedMap =scoreboard
           .entrySet()
           .stream()
           .sorted(Map.Entry.comparingByValue())
           .collect(
                   Collectors.toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2,LinkedHashMap::new));
         
       Iterator<Entry<String, Integer>> iterator = sortedMap.entrySet().iterator();
       List<String> result = new ArrayList<>();
           // Iterate over the HashMap
           while (iterator.hasNext()) {

               // Get the entry at this iteration
               Entry<String, Integer> entry = iterator.next();
              
               result.add(entry.getKey()+" : "+entry.getValue());
              
           }

       return result;

   }

   public int getScore() {
       return this.currentScore;

   }

   public void increaseScore(int additional) {

       if (additional > 0)
           this.currentScore = this.currentScore + additional;
   }

   public void reset() {

       this.currentScore = 0;
   }

   public void setScores(HashMap<String, Integer> scores) {

       Iterator<Entry<String, Integer>> iterator = scores.entrySet().iterator();

       // Iterate over the HashMap
       while (iterator.hasNext()) {

           // Get the entry at this iteration
           Entry<String, Integer> entry = iterator.next();

           boolean flag = entry.getKey().matches("[A-Za-z0-9]{1,}");

           if (flag) {

               if (entry.getValue() >= 0) {

                   scoreboard.put(entry.getKey(), entry.getValue());

               }

               else
                   System.out.println("Invalid score");
           }

           else
               System.out.println("Invalid Name");
       }

   }

   public void setScore(String name, int score) {

       boolean flag = name.matches("[A-Za-z0-9]{1,}");

       if (flag) {

           if (score >= 0) {

               scoreboard.put(name, score);

           }

           else
               System.out.println("Invalid score");
       }

       else
           System.out.println("Invalid Name");
   }

}

Please Give an upvote if you find the answer helpful.


Related Solutions

Package pacman.score Class ScoreBoard Object ScoreBoard public class ScoreBoard extends Object ScoreBoard contains previous scores and...
Package pacman.score Class ScoreBoard Object ScoreBoard public class ScoreBoard extends Object ScoreBoard contains previous scores and the current score of the PacmanGame. A score is a name and value that a valid name only contains the following characters: A to Z a to z 0 to 9 and must have a length greater than 0. The value is a integer that is equal to or greater than 0. Implement this for Assignment 1 Constructor Summary Constructors Constructor Description ScoreBoard() Creates...
Write a class that extends the LeggedMammal class from the previous laboratory exercise.
C++ code on Visual Studio Code:Write a class that extends the LeggedMammal class from the previous laboratory exercise. The class will represent a Dog. Consider the breed, size and is registered. Initialize all properties of the parent class in the new constructor. This time, promote the use of accessors and mutators for the new properties. Instantiate a Dog object in the main function and be able to set the values of the properties of the Dog object using the mutators....
public class Flight extends java.lang.Object This class represents a single flight within the travel agency system....
public class Flight extends java.lang.Object This class represents a single flight within the travel agency system. Constructor Summary Constructors Constructor and Description Flight(java.lang.String airline, int flightNum, java.lang.String from, java.lang.String to, java.util.Calendar leavesAt, java.util.Calendar arrives, double price) Creates a new flight leg in the system. Method Summary All Methods Instance Methods Concrete Methods Modifier and Type Method and Description double getPrice() Retrieves the price of this flight. java.lang.String toString() Retrieves a formatted string summarizing this Flight. Methods inherited from class java.lang.Object...
The following Java program is NOT designed using class/object concept. public class demo_Program4_non_OOP_design { public static...
The following Java program is NOT designed using class/object concept. public class demo_Program4_non_OOP_design { public static void main(String[] args) { String bottle1_label="Milk"; float bottle1_volume=250; float bottle1_capacity=500; bottle1_volume=addVolume(bottle1_label, bottle1_volume,bottle1_capacity,200); System.out.println("bottle label: " + bottle1_label + ", volume: " + bottle1_volume + ", capacity: " +bottle1_capacity); String bottle2_label="Water"; float bottle2_volume=100; float bottle2_capacity=250; bottle2_volume=addVolume(bottle2_label, bottle2_volume,bottle2_capacity,500); System.out.println("bottle label: " + bottle2_label + ", volume: " + bottle2_volume + ", capacity: " +bottle2_capacity); } public static float addVolume(String label, float bottleVolume, float capacity, float addVolume)...
Create a Java class named Package that contains the following: Package should have three private instance...
Create a Java class named Package that contains the following: Package should have three private instance variables of type double named length, width, and height. Package should have one private instance variable of the type Scanner named input, initialized to System.in. No-args (explicit default) public constructor, which initializes all three double instance variables to 1.0.   Initial (parameterized) public constructor, which defines three parameters of type double, named length, width, and height, which are used to initialize the instance variables of...
Consider the following code: public class Bay extends Lake { public void method1() { System.out.println("Bay 1");...
Consider the following code: public class Bay extends Lake { public void method1() { System.out.println("Bay 1"); super.method2(); } public void method2() { System.out.println("Bay 2"); } } //********************************* class Pond { public void method2() { System.out.println("Pond 2"); } } //************************** class Ocean extends Bay { public void method2() { System.out.println("Ocean 2"); } } //********************************* class Lake extends Pond { public void method3() { System.out.println("Lake 3"); method2(); } } //**************************** class Driver { public static void main(String[] args) { Object var4 =...
How can the classes be modified to satisfy the comments: public class InvalidIntegerException extends Exception{    ...
How can the classes be modified to satisfy the comments: public class InvalidIntegerException extends Exception{     // Write a class for an InvalidIntegerException here     //Constructor that takes no arguments public InvalidIntegerException (){ super(); } //Constructor that takes a string message public InvalidIntegerException (String message){ super(message); } } import java.io.InputStream; import java.io.IOException; public class Parser { private InputStream in; public static final int CHAR_ZERO = (int) '0'; public Parser (InputStream in) { this.in = in; } // Complete the following...
Fix the following java code package running; public class Run {    public double distance; //in...
Fix the following java code package running; public class Run {    public double distance; //in kms    public int time; //in seconds    public Run prev;    public Run next;    //DO NOT MODIFY - Parameterized constructor    public Run(double d, int t) {        distance = Math.max(0, d);        time = Math.max(1, t);    }       //DO NOT MODIFY - Copy Constructor to create an instance copy    //NOTE: Only the data section should be...
package design; public class FortuneEmployee { /** * FortuneEmployee class has a main methods where you...
package design; public class FortuneEmployee { /** * FortuneEmployee class has a main methods where you will be able to create Object from * EmployeeInfo class to use fields and attributes.Demonstrate as many methods as possible * to use with proper business work flow.Think as a Software Architect, Product Designer and * as a Software Developer.(employee.info.system) package is given as an outline,you need to elaborate * more to design an application that will meet for fortune 500 Employee Information *...
What is a package? What package is the Scanner class in? What package is the String class in?
What is a package? What package is the Scanner class in? What package is the String class in? 
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT