Study Practice Solution

Question #2 on the 2017 AP Exam was testing your ability to use an arbitrary Java interface called StudyPractice. You were to implement this interface to create a class called MultPractice.

The StudyPractice interface, defined below, specifies two methods that you must implement; getProblem and nextProblem.

public interface StudyPractice {
    
    /** Returns the current practice problem */
    String getProblem();
  
    /** Changes to the next practice problem */
    void nextProblem();
}

Our implementation of MultPractice must implement both of these methods.

public class MultPractice implements StudyPractice {
    
    private int numOne;
    private int numTwo;
    
    public MultPractice(int a, int b) {
        numOne = a;
        numTwo = b;
    }
    
    public String getProblem() {
        return numOne + " TIMES " + numTwo;
    }
    
    public void nextProblem() {
        numTwo++; 
    }
    
}

Let’s start with the first line. We’re creating a class called MultPractice that implements the interface StudyPractice.

For this class we’ll need two int instance variables. Names don’t really matter, but they do both need to be private. That’s a College Board preference that all instance variables should be private.

The constructor takes two int parameters. We know this because of the examples in the problem. There are several example calls similar to StudyPractice p1 = new MultPractice(7, 3);. This tells us that the constructor must take two int parameters.

Then we implement the getProblem and nextProblem methods. getProblem returns a string in a specific format, starting with the first number, followed by " TIMES ", followed by the second number. nextProblem increments the second number so that the next time getProblem is called it returns a different string.

CompSci.rocks Newsletter

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?

Leave a Reply

Your email address will not be published. Required fields are marked *