Chapter 1
Introduction to Programming
Section 1.9
Primitive Data Types
1. (1) [G] A
Section 1.10
Expression and Assignment Statements
1. (36) [T] B
2. (37) [T] A
1
Chapter 2
Using Objects
Section 2.7
String Objects
1. (10) [G] E
Section 2.8
String Methods
1. (2) [G] A
2
Chapter 3
Boolean Expressions and If Statements
Section 3.1
Boolean Expressions
1. (3) [G] D
Section 3.3
The if-else Statements
1. (4) [G] E
3
Section 3.5
Compound Boolean Expressions
1. (5) [G] A
4
Chapter 4
Iteration
Section 4.2
For loop
1. (6) [G] D
2. (7) [G] A
3. (47) [T] C
4. (46) [T]
a. public static int rollFor(int n)
{
int die1, die2;
int count = 0;
int total = 0;
while(total != n)
{
die1 = (int)(Math.random() * 6) + 1;
die2 = (int)(Math.random() * 6) + 1;
total= die1 + die2;
count++;
}
return count;
}
b. public static double getAverageRollCount(int roll)
{
double total = 0.0;
for(int i = 1 ; i <= NUMBER_OF_EXPERIMENTS; i++)
{
total += rollFor(roll);
}
return total / NUMBER_OF_EXPERIMENTS;
}
5. (132) [T]
a. public boolean simulate()
{
int position = 0;
for(int hop = 1; hop <= maxHops; hop++)
{
position += hopLength();
if(position >= goal)
return true;
else if(position < 0)
return false;
}
return false;
}
5
b. public double performSimulations (int num)
{
int count = 0;
for(int n = 0; n < num; n++) {
if(simulate())
count++;
return (double) count / num;
}
}
Section 4.3
Algorithms Using Strings
1. (50) [T]
public class GuessingGame
{
private String secretWord;
public GuessingGame(String theStr)
{ secretWord = theStr; }
public String myGuess(String playerStr)
{
String clueStr = "";
for(int x = 0; x < playerStr.length(); x++)
{
String s1 = playerStr.substring(x, x + 1);
String s2 = secretWord.substring(x, x + 1);
if(s1.equals(s2))
clueStr += playerStr.substring(x, x + 1);
else if(secretWord.indexOf(s1) != -1)
clueStr += "?";
else
clueStr += "!";
}
return clueStr;
}
}
Section 4.4
Nested Iteration
1. (8) [G] A
6
2. (48) [T]
for(int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print("A");
for(int j = 1; j <= 6 - i; j++)
System.out.print("B");
System.out.println();
}
7
Chapter 5
Writing Classes
Section 5.2
Constructors
1. (9) [G] D
Section 5.4
Accessor and Mutator Methods
1. (30) [G] B
Section 5.5
Writing Methods
1. (40) [T]
public class ItemStock
{
private String description;
private int number;
private double price;
private int numberOnShelf;
public ItemStock(String des, int id, double pr, int num)
{
description = des;
number = id;
price = pr;
numberOnShelf = num;
}
public String findDescription() { return description; }
public int findNumber() { return number; }
public double findPrice() { return price; }
public int findNumberOnShelf() { return numberOnShelf; }
public void setPrice(double newPrice) { price = newPrice; }
public void removeQuantity(int quantity)
{
numberOnShelf -= quantity;
if(numberOnShelf < 0)
numberOnShelf = 0;
}
public void addQuantity(int quantity)
{ numberOnShelf += quantity; }
8
public String toString()
{
String display;
display = "Description: " + description;
display += "\nNumber: " + number;
display += "\nPrice: " + price;
display += "\nNumber on shelf: " + numberOnShelf + "\n";
return display;
}
}
public class StockItemTester
{
public static void main(String [] args)
{
ItemStock item = new ItemStock("Kitkat", 125467, 36.0, 54);
System.out.println(item);
item.removeQuantity(24);
System.out.println(item);
item.addQuantity(10);
System.out.println(item);
}
}
2. (11) [G] A
3. (35) [T] C
9
4. (128) [T]
public class WalkFollower
{
private int minimumSteps, allSteps;
private int allDays, activeDays;
public StepTracker(int requiredSteps)
{
minimumSteps = requiredSteps;
allSteps = 0;
allDays = 0;
activeDays = 0;
}
public void addStepsForDay(int stepsNum)
{
allSteps += stepsNum;
allDays++;
if(stepsNum >= minimumSteps)
activeDays++;
}
public int numOfActiveDays()
{
return activeDays;
}
public double stepsMeanValue()
{
if(allDays == 0)
return 0.0;
else
return (double) allSteps / allDays;
}
}
10
5. (130) [T]
public class Team
{
private Employee emp1;
private Employee emp2;
private Employee emp3;
public Team(Employee e1, Employee e2, Employee e3)
{
emp1 = e1;
emp2 = e2;
emp3 = e3;
}
public int TeamJobNum()
{
return emp1.getNumJobs() + emp2.getNumJobs() +
emp3.getNumJobs() + 5;
}
public double getTeamDesirability()
{
int days1 = emp1. getDaysPresent();
int days2 = emp2. getDaysPresent();
int days3 = emp3. getDaysPresent();
double avg1 = emp1.getWorkQuality();
double avg2 = emp2.getWorkQuality();
double avg3 = emp3.getWorkQuality();
double avg = (avg1 + avg2 + avg3) / 3;
if(days1 >= 24 && days2 >= 24 && days3 >= 24)
return avg;
else
return avg - 3;
}
}
11
Chapter 6
Arrays
Section 6.1
Array Creation and Access
1. (14) [G] D
Section 6.2
Traversing Arrays
1. (12) [G] E
2. (13)
[G] A
3. (84) [T] 2 4 6 8 100 Los Angeles
Section 6.4
Developing Algorithms Using Arrays
1. (52) [T]
a. public double averageTuition()
{
double sum = 0.0;
for(int i = 0; i < myColleges.length ; i++)
sum += myColleges[i].getTuition();
return sum / myColleges.length;
}
b. public int numColleges(int rank)
{
int counter = 0;
for(int i = 0; i < myColleges.length ; i++)
{
if(myColleges[i].getTuition() > averageTuition()
&& myColleges[i].getTuition() == rank)
counter++;
return counter;
}
}
2. (55) [T] A
12
3. (57) [T]
public int isLongest(int tg)
{
int lenCount = 0, maxLen = 0;
for(int k = 0; k < numbers.length; k++)
{
if(numbers[k] == tg)
lenCount++;
else
{
if(lenCount > maxLen)
maxLen = lenCount;
lenCount = 0;
}
}
if(lenCount > maxLen)
maxLen = lenCount;
return maxLen;
}
4. (135) [T]
a. public static boolean isArmstrong(int number)
{
int n = number;
int sum = 0;
while(n > 0)
{
int d = n % 10;
sum += Math.pow(d, 3);
n /= 10;
}
return sum == number;
}
b. public static int [] firstNumArmstrong(int num)
{
int [] a = new int[num];
int count = 0;
int n = 0;
while(count < num)
{
if(isArmstrong(n))
{
a[count] = n;
count++;
}
n++;
}
return a;
}
13
6. (43) [T]
a. public boolean areAcceptable(int s, int e)
{
int max = marks[s], min = marks[s];
for(int i = s + 1; i <= e; i++)
{
if(marks[i] > max)
max = marks[i];
if(marks[i] < min)
min = markers[i];
}
return max - min <= 10;
}
b. public boolean isDifficult()
{
int count = 0;
for(int i = 0; i < marks.length - 1; i++)
{
if(Math.abs(marks[i + 1] - marks[i]) >= 30)
count++;
}
return count >= 3;
}
14
Chapter 7
ArrayLists
Section 7.2
ArrayLists Methods
1. (15) [G] B
Section 7.3
Traversing ArrayLists
1. (16) [G] C
2. (17)
[G] D
3. (22) [G] B
Section 7.4
Developing Algorithms using ArrayLists
1. (82) [T]
a. public Digits(int num)
{
digitList = new ArrayList<Integer>();
while(num > 0)
{
digitList.add(0, num % 10);
num /= 10;
}
if(digitList.size() == 0)
digitList.add(0);
}
b. public boolean isStrictlyIncreasing()
{
for(int k = 1; k < digitList.size(); k++)
{
if(digitList.get(k).intValue() <=
digitList.get(k-1).intValue())
return false;
}
return true;
}
2. (70) [T]
a. 2755633
b. Add an else before x++;
3. (72) [T] C
15
4. (66) [T]
a. public int countElectronicsByMaker(String maker)
{
int result = 0;
for (Gizmo g : purchases)
{
if(g.getMaker().equals(maker) && g.isElectronic())
result++;
}
return result;
}
b. public boolean hasAdjacentEqualPair()
{
for(int pos = 1; pos < purchases.size(); pos++)
{
Gizmo g1 = purchases.get(pos-1);
Gizmo g2 = purchases.get(pos);
if(g1.equals(g2))
return true;
}
return false;
}
5. (139) [T]
a. public int getAverage()
{
double total = 0;
for(PencilOrder p : ordersList)
total += p. getNumberOfBoxes();
return total / ordersList.size();
}
b. public void removeBrand(String brand)
{
for(int i = ordersList.size() - 1; i >= 0; i--)
{
PencilOrder p = ordersList.get(i);
if(p.getBrand().equals(brand))
ordersList.remove(i);
}
}
16
Section 7.5
Searching
1. (19) [G] C
2. (123) [T]
a. III only
b. D
3. (20) [G] E
4. (21) [G] B
5. (125) [T]
a. 1
b. 3
c. 2
Section 7.6
Sorting
1. (22) [G] E
17
Chapter 8
2D Arrays
Section 8.1
2D Arrays
1. (23) [G] C
Section 8.2
Traversing 2D Arrays
1. (24) [G] B
2. (54)
[T]
newNums = { { 11, 12, 13, 14, 15 },
{ 16, 17, 18, 19, 20 },
{ 21, 22, 23, 24, 25 } };
5. (59) [T]
a. public static int totalArr(int[] myArray)
{
int total = 0;
for(int item : myArray)
total += item;
return total;
}
b. public static int[] TotalArrRows(int[] [] theMatrix)
{
int [] totalsArray = new int[theMatrix.length];
int index = 0;
for(int [] M : theMatrix)
{
totalsArray[index] = TotalArr(M);
index++;
}
return totalsArray;
}
c. public static boolean isVaried(int[] [] theMatrix)
{
int [] totalsArray = TotalArrRows(theMatrix);
for(int x = 0; x < totalsArray.length; x++)
{
for(int y = x + 1; y < totalsArray.length; y++)
if(totalsArray[x] == totalsArray[y])
return false;
}
return true;
}
18
3. (62) [T]
a. public static void insertBeginningOfArray(int[] theArray, int newVal)
{
for (int index = theArray.length - 1; index > 0; index--)
{
theArray[index] = theArray[index - 1];
}
theArray[0] = newVal;
b. public void insertBeginningOfMtrx(int newVal)
{
for (int[] arr : theMtrx)
{
int X = arr[arr.length - 1];
ArrFunctions.insertBeginningOfArray(arr, newVal);
newVal = X;
}
}
c. public void revolveTheMtrx()
{
insertBeginningOfMtrx
(theMtrx[theMtrx.length - 1][theMtrx[0].length - 1]);
}
4. (65) [T]
a. 1 2 3 4
11 12 13 14
21 22 23 24
b. 11 12 13 14
11 12 13 14
21 22 23 24
5. (138) [T]
a. public void initialize1DArray(boolean [] array1D, int n)
{
array1D = new boolean[n];
for(int i = 0; r < n; i++)
array1D[i] = Math.random() < 0.4;
}
b. public int countTrueInColumn(boolean [][] array2D, int c)
{
int count = 0;
for(int r = 0; r < array2D.length; r++)
{
if(lights[r][c])
count++;
}
return count;
}
19
c. public int [] getValuesOfColumn(int [][] array2D, int c)
{
int [] column = new int[arr2D.length];
for(int r = 0; r < column.length; r++)
column[r] = arr2D[r][c];
return column;
}
20
Chapter 9
Inheritance
Section 9.1
Super classes and Subclasses
1. (25) [G] E
2. (26) [G] B
3. (90) [T] A
4. (42) [T]
I. public class BankAccount
{
private double balance;
public BankAccount() { balance = 0; }
public BankAccount(double initialBalance)
{
if(initialBalance >= 0)
balance = initialBalance;
}
public void deposit(double amount)
{
if(amount > 0)
balance = balance + amount;
}
public void withdraw(double amount)
{
if(amount > 0 && amount <= balance)
balance = balance - amount;
}
public double getBalance() {return balance; }
public void transfer(double amount, BankAccount other)
{
if(amount > 0 && amount <= balance)
{
withdraw(amount);
other.deposit(amount);
}
}
}
21
II. public class CheckingAccount extends BankAccount
{
private int transactionCount;
public CheckingAccount(double initialBalance)
{
super(initialBalance);
transactionCount = 0;
}
public void deposit(double amount)
{
transactionCount++;
super.deposit(amount);
}
public void withdraw(double amount)
{
transactionCount++;
super.withdraw(amount);
}
public void deductFees()
{
if(transactionCount > 3)
{
super.withdraw((transactionCount – 3) * 2.5);
transactionCount = 0;
}
}
}
III. public class SavingsAccount extends BankAccount
{
private double interestRate;
public SavingsAccount(double initialBalance, double rate)
{
super(initialBalance);
interestRate = rate;
}
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
deposit(interest);
}
}
Section 9.2
Writing Constructors for Subclasses
1. (28) [G] D
2. (96) [T]
super(theName, thePhoneNumber);
nickname = theNickname;
3. (89) [T] E
22
Section 9.3
Overriding Methods
1. (29) [G] B
Section 9.6
Polymorphism
1. (27) [G] C
2. (75) [T] C
3. (77) [T] jump shake twist repeat
4. (31) [G] C
5. (79) [T]
a. public class Kitten extends Pet
{
public Kitten(String itsName)
{
super(itsName);
}
public String talk()
{
return "meow";
}
}
b. public class NoisyDog extends Dog
{
public NoisyDog(String itsName)
{
super(itsName);
}
public String talk()
{
String dogSound = super.talk();
return dogSound + dogSound;
}
}
c. public void allTalk()
{
for (Pet pet : petsList)
{
System.out.println(pet.findName() + " " +
pet.talk());
}
}
6. (97) [T] I and II
23
Chapter 10
Recursion
Section 10.1
Recursion
1. (32) [G] A
Section 10.4
Recursive Algorithms
1. (33) [G] C
2. (103) [T] 16533561
3. (105) [T] 2101
4. (107) [T] 1
5. (109) [T] 1315131
6. (111) [T] C
7. (113) [T] It prints the string s in reverse order.
8. (115) [T] todayodayay
9. (117) [T] 16
10. (119) [T] 15
11. (120) [T] C
12. (121) [T] 10
13. (122) [T] 6
24