Java

OOP GUIDE / WORK

 

DIGITS CLASS

 

Topics

  • Class design
  • ArrayLists

 

Source

  • This question was part of the 2017 AP exam free response questions.  You can find a link to all free response questions on the previous page.

 

 

TASK – PART 1 – SETUP – DIGITS CLASS STARTER CODE

 

No solution required.

 

 

TASK – PART 2 – WORK

 

Here is my solution:

 

import java.util.ArrayList;

 

public class Digits

{

     /** The list of digits from the number used to construct this object.

      * The digits appear in the list in the same order in which they appear

      * in the original number.

      */

    

     private ArrayList<Integer> digitList;

 

    

     /** Constructs a Digits object that represents num.

      * Precondition: num >= 0

      */

 

     public Digits(int num)

 

     {

           digitList = new ArrayList<Integer>();

           if (num == 0)

                digitList.add(0);

           while(num != 0)

           {

                int digit = num % 10;

                digitList.add(0, digit);

                num = num / 10;

           }

     }

 

     /** Returns true if the digits in this Digits object are in strictly increasing order;

      * false otherwise.

      */

 

     public boolean isStrictlyIncreasing()

     {

           if (digitList.size() < 2)

           {   

                return true;

           }

           else

           {

                for (int i=0; i<digitList.size()-1; i++)

                {

                      if (digitList.get(i) >= digitList.get(i+1))

                      {

                           return false;

                      }

                }

                return true;

           }

     }

    

     public String toString()

     {

           return digitList.toString();

     }

}

 

 

 

TASK – PART 4 – TESTING YOUR CLASS

 

No solution required.