Create a class named PremiumSugarSmashPlayer that descends from SugarSmashPlayer. This class is instantiated when a user pays $2.99 to have access to 40 additional levels of play. As in the free version of the game, a user cannot set a score for a level unless the user has earned at least 100 points at all previous levels.

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Question

This is the question -

The developers of a free online game named Sugar Smash have asked you to develop a class named SugarSmashPlayer that holds data about a single player. The class contains the following fields:

  • idNumber - the player’s ID number (of type int)
  • name - the player's screen name (of type String)
  • scores - an array of integers that stores the highest score achieved in each of 10 game levels

Include get and set methods for each field. The get method for scores should require the game level to retrieve the score for. The set method for scores should require two parameters—one that represents the score achieved and one that represents the game level to be retrieved or assigned.

Display an error message if the user attempts to assign or retrieve a score from a level that is out of range for the array of scores. Additionally, no level except the first one should be set unless the user has earned at least 100 points at each previous level. If a user tries to set a score for a level that is not yet available, issue an error message.

Create a class named PremiumSugarSmashPlayer that descends from SugarSmashPlayer. This class is instantiated when a user pays $2.99 to have access to 40 additional levels of play. As in the free version of the game, a user cannot set a score for a level unless the user has earned at least 100 points at all previous levels.

This is the code I have. I seem to be having issues with my get score and set score. I will attach a screenshot of the kind of error I am getting. -

import java.util.*;
public class DemoSugarSmash
{
   public static void main(String[] args)
   {
      SugarSmashPlayer player1 = new SugarSmashPlayer();
      player1.setIdNumber(12);
      player1.setName("Hagemaru");
      player1.setScore(2340,1);
      player1.setScore(400,2);
      player1.setScore(500,5);
      System.out.print("\n\t Id : "+player1.getIdNumber()+"\n\tName: "+player1.getName()

      +"\n\tLevel1: "+player1.getScore(1)+"\n\tLevel2: "+player1.getScore(2));

      System.out.print("\nDo you wish to pay $2.99 to have access to 40 additional levels of play? (y/n) :");

      Scanner s = new Scanner(System.in);
      char c=s.next().charAt(0);
      if(c=='y'||c=='Y'){
        player1=new PremiumSugarSmashPlayer();
      }
   }
}
 
class PremiumSugarSmashPlayer extends SugarSmashPlayer

{
    double[] moreScores= new double[50];
    PremiumSugarSmashPlayer(){
        super();
        int i;
        for( i=0;i<10;i++){
            moreScores[i]=super.scores[i];
        }
        for( ;i<50;i++){
            moreScores[i]=0;
        }
    }

    public double getScore(int level){
        if(level<0 || level>50)
            System.out.print("This level not exists!");
        else{
             return moreScores[level-1];
        }
        return -1;
   }

   public void setScore(double score,int level){
        if(level<0 || level>50)
            System.out.print("\nThis level not exists!");
        else{
            moreScores[level-1]=score;
        }
   }
}
 
class SugarSmashPlayer
{
   protected int idNumber;
   protected String name;
   protected double[] scores= new double[10];
   public SugarSmashPlayer(){
       idNumber=0;
       name="";
       for(int i=0;i<10;i++)
            scores[i]=0;
   }

   public int getIdNumber()
   { 
       return idNumber;
   }

   public String getName()
   { 
       return name;
   }

   public double getScore(int level){
        if(level<0 || level>10)
            System.out.print("This level not exists!");
        else
            return scores[level-1];
        return -1;
   }

   public void setIdNumber(int x)
   { 
       idNumber=x;
   }

   public void setName(String s)
   { 
       name=s; 
   }

   public void setScore(double score,int level){
        if(level<0 || level>10)
            System.out.print("\nThis level not exists!");
        else{
            if(level!=1 && scores[level-2]<100)
                System.out.print("\nYou can't play for this level untill previos level score is less than 100");
            else
                scores[level-1]=score;
        }
   }
}
 
Here is part of my error typed out then screenshot - 

Define getScore method in class SugarSmashPlayer

Build Status
Build Succeeded
Test Outputjava.lang.ArrayIndexOutOfBoundsException: -1 SugarSmashPlayer.getScore(SugarSmashPlayer.java:27) at NtTeste831b2f3.unitTest(NtTeste831b2f3.java:13) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod
The image displays a Java code snippet that demonstrates the use of reflection to access a private field and handle exceptions. Here's a detailed transcription of the code:

```java
public static java.lang.reflect.Field accessPrivateField(String fieldName) {
    java.lang.reflect.Field field = null;
    // Allow test access to private field
    try {
        field = className.getDeclaredField(fieldName);
        field.setAccessible(true);
        return field;
    } catch (Exception e) {
        Tester.displayError(e);
    }
    return field;
}

public static void displayError(Exception e) {
    System.out.print(e + "\n\n");
    StackTraceElement[] elements = e.getStackTrace();
    for (int i=0; i<elements.length; i++) {
        System.out.println(elements[i]);
        if (elements[i].toString().contains("CodevolveTest")) {
            System.out.print("\n");
        }
    }
}
```

### Code Explanation:

1. **Method `accessPrivateField`:**
   - **Purpose:** Uses reflection to access a private field of a class by its name.
   - **Parameters:** `String fieldName` - the name of the private field to access.
   - **Steps:**
     - Declares a `Field` object.
     - Attempts to retrieve the field with `getDeclaredField(fieldName)`.
     - Sets the field accessible.
     - Catches any exceptions that occur and calls `Tester.displayError(e)` to handle errors.

2. **Method `displayError`:**
   - **Purpose:** Prints out exceptions and their stack trace.
   - **Parameters:** `Exception e` - the exception to display.
   - **Steps:**
     - Prints the exception message.
     - Iterates over the stack trace elements and prints each element.
     - Additional checking if the stack trace element contains "CodevolveTest", where it prints an extra newline for formatting.

### Graphical Interface:

- **Buttons:**
  - **Run Checks:** Presumably executes the code or checks for errors.
  - **Submit 40%:** Possibly related to submitting the code for review or evaluation, indicated by "40%". 

This code snippet can be used in educational scenarios to teach Java Reflection, exception handling, and stack trace analysis.
Transcribed Image Text:The image displays a Java code snippet that demonstrates the use of reflection to access a private field and handle exceptions. Here's a detailed transcription of the code: ```java public static java.lang.reflect.Field accessPrivateField(String fieldName) { java.lang.reflect.Field field = null; // Allow test access to private field try { field = className.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (Exception e) { Tester.displayError(e); } return field; } public static void displayError(Exception e) { System.out.print(e + "\n\n"); StackTraceElement[] elements = e.getStackTrace(); for (int i=0; i<elements.length; i++) { System.out.println(elements[i]); if (elements[i].toString().contains("CodevolveTest")) { System.out.print("\n"); } } } ``` ### Code Explanation: 1. **Method `accessPrivateField`:** - **Purpose:** Uses reflection to access a private field of a class by its name. - **Parameters:** `String fieldName` - the name of the private field to access. - **Steps:** - Declares a `Field` object. - Attempts to retrieve the field with `getDeclaredField(fieldName)`. - Sets the field accessible. - Catches any exceptions that occur and calls `Tester.displayError(e)` to handle errors. 2. **Method `displayError`:** - **Purpose:** Prints out exceptions and their stack trace. - **Parameters:** `Exception e` - the exception to display. - **Steps:** - Prints the exception message. - Iterates over the stack trace elements and prints each element. - Additional checking if the stack trace element contains "CodevolveTest", where it prints an extra newline for formatting. ### Graphical Interface: - **Buttons:** - **Run Checks:** Presumably executes the code or checks for errors. - **Submit 40%:** Possibly related to submitting the code for review or evaluation, indicated by "40%". This code snippet can be used in educational scenarios to teach Java Reflection, exception handling, and stack trace analysis.
```java
public void unitTest() {
    java.lang.reflect.Field scoresField = null;
    SugarSmashPlayer player = new SugarSmashPlayer();
    try {
        scoresField = Tester.accessPrivateField("scores", SugarSmashPlayer.class);
        
        player.scores[0] = 50;
        assertEquals(player.getScore(0), 50);
        player.scores[0] = 100;
        assertEquals(player.getScore(0), 100);
        
    // Display errors
    } catch (Exception e) {
        Tester.displayError(e);
    }
}

public static class Tester {
```

- This code snippet is designed to conduct unit testing on the `SugarSmashPlayer` class. It uses reflection to access a private field named "scores".
  
- It tests the `getScore` method by setting a score directly and verifying if the method returns the correct value using `assertEquals`.

- The `try-catch` block is used to handle any potential exceptions that may arise during the test, with errors being displayed by the `Tester.displayError` method.

Buttons at the bottom:
- **Run Checks**: Likely executes the unit test to verify functionality.
- **Submit 40%**: Possibly related to submission status or code completion percentage.
Transcribed Image Text:```java public void unitTest() { java.lang.reflect.Field scoresField = null; SugarSmashPlayer player = new SugarSmashPlayer(); try { scoresField = Tester.accessPrivateField("scores", SugarSmashPlayer.class); player.scores[0] = 50; assertEquals(player.getScore(0), 50); player.scores[0] = 100; assertEquals(player.getScore(0), 100); // Display errors } catch (Exception e) { Tester.displayError(e); } } public static class Tester { ``` - This code snippet is designed to conduct unit testing on the `SugarSmashPlayer` class. It uses reflection to access a private field named "scores". - It tests the `getScore` method by setting a score directly and verifying if the method returns the correct value using `assertEquals`. - The `try-catch` block is used to handle any potential exceptions that may arise during the test, with errors being displayed by the `Tester.displayError` method. Buttons at the bottom: - **Run Checks**: Likely executes the unit test to verify functionality. - **Submit 40%**: Possibly related to submission status or code completion percentage.
Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 4 steps with 5 images

Blurred answer
Knowledge Booster
Passing Array as Argument
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education