APCS Lessons 9, 15-16 Test Review Part 1

 

 

  1. Consider the following code that uses the Integer class (a wrapper class for ints):

ArrayList <Integer> a = new ArrayList<Integer>();

 

What are the contents of the ArrayList after the following lines have been executed:

      a.add(new Integer(7));

      a.add(new Integer(5));

      a.add(1, new Integer(9));

      a.get(a.size()-1);

      a.add(new Integer(2));

      a.set(2, new Integer(3));

      a.remove(a.size()-1);

 

 

  1. Consider the design of the class used to maintain scores for video games:

public class Score {

     private int score;

     private String name;

 

     public Score(int scre, String nme)     {…}

 

public int getScore() {…} //returns score

     public String getName() {…} //returns name

     public int compareTo(Score compareMe) {…}

     //returns < 0 if this comes before compareMe

     //returns 0 if this equals compareMe

     //returns > 0 if this comes after compareMe

}

 

public class VideoGameScores {

     private Score[] highScores;

//top scores in descending order

    

     public boolean areAllHeldBySamePerson() {…}

//returns true if all top scores are held by the same //person

public void syncHighScores(Score[] source1, Score[] source2) {…}

//will take high scores from two different sources and

//update highScores with the overall high scores

}   

 

    1. Implement the method compareTo in the Score class.  The method will compare the scores between two objects of the class Score.

Example:

Score s1 = new Score(10000, “abc”);

Score s2 = new Score(8000, “mbs”);

Score s3 = new Score(10000, “cs!”);

s1.compareTo(s2); //returns -1

s1.compareTo(s3); //returns 0

s2.compareTo(s3); //returns 1

 

 

public int compareTo(Score compareMe) {

 

 

 

 

 

}

 

    1. The method areAllHeldBySamePerson()traverses the highScores array and returns true if all the high scores are held by the same person (each score has the exact same name associated with it).  Otherwise, it returns false.

public Boolean areAllHeldBySamePerson() {

 

 

 

 

}

    1. The method syncHighScores()takes high scores from two different sources like your phone and your computer and synchronizes them.  It fills in the highScores array with the highest scores from both in descending order (high score first).  You can assume both source1 and source2 are in descending order.

public void syncHighScores(Score[] source1, Score[] source2) {

 

 

 

}

 

 

  1. Write a method that will take an array of ints and find the sum.

 

  1. What does the following method do (for what types of array would it return false and for what type will it return true)?

 

public boolean doSomething(int[] a) {

   boolean flag = true;

   for (int j = 0; j < a.length - 1; j++)

      flag = flag && (a[j] < a[j+1]);

   return flag;

}