You are on page 1of 4

2004 AP Computer Science A Free-Response Answers

1) WORDLIST a) numWordsOfLength public int numWordsOfLength(int len){ int count = 0; for(int k=0; k < myList.size(); k++){ String s = (String) myList.get(k); if (s.length() == len){ count++; } } return count; } b) removeWordsOfLength public void removeWordsOfLength(int len){ for(int j=0; j<myList.size(); j++){ String s = (String) myList.get(j); if (s.length() == len){ myList.remove(j); j--; } } }

OR
public void removeWordsOfLength(int len) { int i = 0; while (i < myList.size()) 1 { if (((String)myList.get(i)).length() == len) myList.remove(i); 2 else i++; }

2) PETS a) CAT
public class Cat extends Pet { public Cat(String name){ super(name); } public String speak(){ return "meow"; }

b) LOUD DOG
public class LoudDog extends Dog { public LoudDog(String name){ super(name); } public String speak(){ return super.speak()+super.speak(); }

c) KENNEL
import java.util.*; public class Kennel { private ArrayList petList; public void allSpeak(){ for(int k=0; k < petList.size(); k++){ Pet p = (Pet) petList.get(k); System.out.println(p.getName() + " " + p.speak()); } } }

3) PONDSTOCKER a) NumUnder
private int numUnder(){ int cells = theEnv.numRows() * theEnv.numCols(); int fish = theEnv.numObjects(); int needed = 1 + (int) (cells*minDensity); if (fish >= needed) return 0; else return needed-fish; }

b) randomLocation
private Location randomLocation(){ Random rando = RandNumGenerator.getInstance(); Location loc = new Location(rando.nextInt(theEnv.numRows()), rando.nextInt(theEnv.numCols())); return loc; }

c) addFish
public void addFish(int numToAdd){ int count = 0; while (count < numToAdd){ Location loc = randomLocation(); if (theEnv.isEmpty(loc)){ new Fish(theEnv,loc); // adds itself to environment count++; } } }

4) ROBOT a) forwardMoveBlocked
private boolean forwardMoveBlocked(){ if (facingRight){ return pos == hall.length-1; } else { return pos == 0; } }

b) move
private void move(){ if (hall[pos] > 0){ hall[pos]--; } if (hall[pos] == 0){ if (forwardMoveBlocked()){ facingRight = !facingRight; } else { if (facingRight){ pos++; } else { pos--; } } } }

c) clearHall
public int clearHall(){ int count = 0; while (! hallIsClear()){ move(); count++; } return count; }

You might also like