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.

I don't know how to deal with this part.

Solutions

Expert Solution

//////////////////////////////////////////

package pacman.score;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

public class ScoreBoard {
  
   private Map<String,Integer> allScores = null;
   private int currentScore = 0;
  
   //constructor
   //initializes the score board
   public ScoreBoard() {
       this.allScores = new HashMap<>();
       this.currentScore = 0;
   }
  
   //get current score
   public int getScore(){
       return currentScore;
   }
  
   //reset current score
   public void reset(){
       currentScore = 0;
   }
  
   //increase current score if addition > 0
   public void increaseScore(int additional){
       if(additional > 0 ){
           currentScore += additional;
       }
   }
  
   //add the name, score pair in allScores map after doing validation check
   public void setScore(String name, int score){
       if(isValid(name,score)){
           allScores.put(name, score);
       }
   }
  
  
   //sets allScores from given map of scores
   //after doing validation check of=n key-value pair
   public void setScores(Map<String,Integer> scores){
      
       if(scores!=null && scores.keySet()!=null){
           for(String name:scores.keySet()){
               int score = scores.get(name);
               if(isValid(name,score)){
                   allScores.put(name, score);
               }
           }
       }
      
   }
  
   //get List of entries by lexicographical order of name
   public List<String> getEntriesByName(){
       List<String> entries = new ArrayList<String>();
      
       List<Map.Entry<String, Integer> > list =
   new LinkedList<Map.Entry<String, Integer> >(allScores.entrySet());
      
       //sort by ascending order of name
       Collections.sort(list, new Comparator<Map.Entry<String,Integer>>(){

           @Override
           public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
               return arg0.getKey().compareTo(arg1.getKey());
           }
          
       });
      
       for(Map.Entry<String,Integer> data: list){
           entries.add(data.getKey()+" : "+data.getValue());
       }
       return entries;
   }
  
   /**
   * getList of entries by descending order of score
   * @return
   */
   public List<String> getEntriesByScore(){
       List<String> entries = new ArrayList<String>();
       List<Map.Entry<String, Integer> > list =
   new LinkedList<Map.Entry<String, Integer> >(allScores.entrySet());
      
       Collections.sort(list, new Comparator<Map.Entry<String,Integer>>(){

           @Override
           public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
               return arg1.getValue().compareTo(arg0.getValue());
           }
          
       });
      
       for(Map.Entry<String,Integer> data: list){
           entries.add(data.getKey()+" : "+data.getValue());
       }
      
      
       return entries;
      
   }
  
   /**
   * Check if name and score is valid
   * @param name
   * @param score
   * @return
   */
   private boolean isValid(String name,int score){
       boolean isValid = false;
       Pattern pattern = Pattern.compile("[A-Za-z0-9]*");
       if(name!=null && name.length() > 0 && pattern.matcher(name).matches()){ //matches pattern for name
           if(score >= 0){
               isValid = true;
           }else{
               System.out.println("Invalid score: "+ score+ " for name: "+name);
           }
       }else{
           System.out.println("Invalid name: "+ name);
       }
       return isValid;
   }

}

///////////////////////////////////////////////////

package pacman.score;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestData {
   public static void main(String[] args){
       ScoreBoard sb = new ScoreBoard();
      
       sb.setScore("Fred", 20);
       sb.setScore("Alex", 18);
       sb.setScore("Bob", 11);
       sb.setScore("Tom", 17);
      
       System.out.println("Showing entries by name:");
       List<String> entries1 = sb.getEntriesByName();
       System.out.println("["+String.join(", ", entries1.stream().toArray(String[]::new))+"]");
      
       System.out.println();
      
       Map<String,Integer> otherEntries = new HashMap<String,Integer>();
       otherEntries.put("Bob09$", 11);
       otherEntries.put("Sam", -11);
       otherEntries.put("Amy", 16);
       otherEntries.put("Tom", 13);
      
       sb.setScores(otherEntries); //set scores from the otherEntries map
      
       System.out.println();
      
       System.out.println("Showing entries by score after adding other Entries:");
       List<String> entries2 = sb.getEntriesByScore();
       System.out.println("["+String.join(", ", entries2.stream().toArray(String[]::new))+"]");
      
       System.out.println();
      
       System.out.println("current score:"+sb.getScore());
      
       sb.increaseScore(4);//increase current score by 4
      
       System.out.println("Current score after increase:"+sb.getScore());
      
       sb.increaseScore(6); //increase current score by 6
      
       System.out.println("Current score after increase:"+sb.getScore());
      
       sb.reset(); //reset current score
      
       System.out.println("Current score after reset:"+sb.getScore());
      
   }

}

=================================

OUTPUT

=================================

Showing entries by name:
[Alex : 18, Bob : 11, Fred : 20, Tom : 17]

Invalid score: -11 for name: Sam
Invalid name: Bob09$

Showing entries by score after adding other Entries:
[Fred : 20, Alex : 18, Amy : 16, Tom : 13, Bob : 11]

current score:0
Current score after increase:4
Current score after increase:10
Current score after reset:0


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 Mammal extends SeaCreature { public void method1() { System.out.println("warm-blooded"); } } public class SeaCreature...
public class Mammal extends SeaCreature { public void method1() { System.out.println("warm-blooded"); } } public class SeaCreature { public void method1() { System.out.println("creature 1"); } public void method2() { System.out.println("creature 2"); } public String toString() { return "ocean-dwelling"; } } public class Whale extends Mammal { public void method1() { System.out.println("spout"); } public String toString() { return "BIG!"; } } public class Squid extends SeaCreature { public void method2() { System.out.println("tentacles"); } public String toString() { return "squid"; } } What...
write the following programs: Ram.java, Truck.java, LandVehicle.java and Vehicle.java. public class Ram extends Truck { public...
write the following programs: Ram.java, Truck.java, LandVehicle.java and Vehicle.java. public class Ram extends Truck { public static void main(String[] args) { // your implementation } public Ram() { // your implementation } } public class Truck extends LandVehicle { public Truck() { // your implementation } public Truck(String s) { // your implementation } } public class LandVehicle extends Vehicle { public LandVehicle() { // your implementation } } public class Vehicle { public Vehicle() { // your implementation
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 =...
Consider the following classes: public class Clock extends Bear { public void method3() { System.out.println("Clock 3");...
Consider the following classes: public class Clock extends Bear { public void method3() { System.out.println("Clock 3"); } } public class Lamp extends Can { public void method1() { System.out.println("Lamp 1"); } public void method3() { System.out.println("Lamp 3"); } } public class Bear extends Can { public void method1() { System.out.println("Bear 1"); } public void method3() { System.out.println("Bear 3"); super.method3(); } } public class Can { public void method2() { System.out.println("Can 2"); method3(); } public void method3() { System.out.println("Can 3"); }...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT