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....
Using Java, Complete LinkedListSet: package Homework3; public class LinkedListSet <T> extends LinkedListCollection <T> { LinkedListSet() {...
Using Java, Complete LinkedListSet: package Homework3; public class LinkedListSet <T> extends LinkedListCollection <T> { LinkedListSet() { } public boolean add(T element) { // Code here return true; } } Homework3 class: public class Homework3 { public static void main(String[] args) { ArrayCollection ac1 = new ArrayCollection(); // Calling Default Constructor ArrayCollection ac2 = new ArrayCollection(2); // Calling overloaded constructor ArraySet as1 = new ArraySet(); ac2.add("Apple"); ac2.add("Orange"); ac2.add("Lemon"); // This can't be added into ac2 as collection is full System.out.println(ac2.remove("Apple")); //...
Create a class to represent a Mammal object that inherits from (extends) the Animal class. View...
Create a class to represent a Mammal object that inherits from (extends) the Animal class. View javadoc for the Mammal class and updated Animal class in homework 4 http://comet.lehman.cuny.edu/sfakhouri/teaching/cmp/cmp326/s19/hw/hw4/ Use the description provided below in UML. Mammal - tailLength : double - numLegs : int + Mammal() + Mammal(double, int) + Mammal(String, int, double, double, char, double, int) //pass values to parent’s overloaded constructor //and assign valid values to tailLength, numLegs or -1 if invalid + setTailLength(double) : void //if...
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...
using java Design a class named Triangle that extends GeometricObject. The class contains: • Three double...
using java Design a class named Triangle that extends GeometricObject. The class contains: • Three double data fields named side1, side2, and side3 to denote three sides of a triangle. • A no-arg constructor that creates a default triangle with default values 1.0. • A constructor that creates a triangle with the specified side1, side2, and side3. In a triangle, the sum of any two sides is greater than the other side. The Triangle class must adhere to this rule...
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...
You coded the following class: public class N extends String, Integer { } When you compile,...
You coded the following class: public class N extends String, Integer { } When you compile, you get the following message: N.java:1: ‘{‘ expected public class N extends String, Integer                                                ^ 1 error Explain what the problem is and how to fix it.
package questions; public class File {    public String base; //for example, "log" in "log.txt"   ...
package questions; public class File {    public String base; //for example, "log" in "log.txt"    public String extension; //for example, "txt" in "log.txt"    public int size; //in bytes    public int permissions; //explanation in toString    //DO NOT MODIFY    public String getBase() {        return base;    }    /**    *    * @param b    * if b is null or if empty (""), base should become "default",    * for all other values...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT