In Part I of Challenge 67, option A best describes the method. The program starts by assigning the int variable n as the length of the String list items. The int variable m is created, equaling n − 1. Then, a for statement is used to make m equal to the element number of the greatest value of items. After that, a String variable named temp is used to switch the values of elements m and n − 1. This process is repeated with the value of n decreased by 1 until n = 1, resulting in the list being sorted in alphabetical order. Because this process best describes Sequential Search, option A is correct.
In Part II of Challenge 67, after two iterations of the while loop, the order of names will be: {“Boris”, “Alice”, “Claire”, “Dan”, “Evan”}. This is because of names’s original order: {“Dan”, “Alice”, “Claire”, “Evan”, “Boris”}. The first iteration of the while statement will compare element 4 (“Boris”) with the others and switch it with the largest of the elements before it: element 3 (“Evan”). The second iteration of the while statement will compare element 3 (“Boris”) with the others and again switch it with the largest of the elements before it: element 0 (“Dan”). This will result in the order of names being: {“Boris”, “Alice”, “Claire”, “Dan”, “Evan”}.
−Phoenix
Friday, May 11, 2012
Monday, May 7, 2012
Challenge 066’s Solution
Of the five options, the most efficient would be option B: to use a Selection Sort that terminates after 5 iterations. Option A offers to use a complete Selection Sort. A Selection Sort starts by getting an array list of size n. It searches each element in this list, and places the largest at position n, then repeats for an array list of size n − 1 until the array has a size of 1. If performed, all 2,000 cows would be ordered. Since we only need the 5 heaviest cows, option A isn’t the most efficient. Option B offers to use Selection Sort, but only for five executions. If performed, the top 5 heaviest cows would be ordered, while the remaining cows would not. Since there is no unnecessary sorting, option B is the most efficient. Option C offers to use a complete Insertion Sort. An Insertion Sort starts by getting an array list and an int variable n of size 1. The value of the element n + 1 is saved separately. Then, among the first n elements of the array, the saved value is inserted in numeric order, and values greater than it are pushed one element right. This repeats with n + 1 until n is the size of the array. If performed, all 2,000 cows would be ordered. Since we only need the 5 heaviest cows, option C isn’t the most efficient. Option D offers to use Insertion Sort, but only for five executions. If performed, only the first 5 cows who were weighed would be ordered, while the remaining cows would not. Since the first 5 cows ordered may not necessarily be the 5 heaviest, option D is inefficient. Finally, option E offers to use a complete Mergesort. A Mergesort starts by splitting the array into two equal halves. Each half is sorted separately, then combined into one sorted whole. If performed, all 2,000 cows would be ordered. Since we only need the 5 heaviest cows, option E isn’t the most efficient.
−Phoenix
−Phoenix
Thursday, May 3, 2012
Challenge 065’s Solution
A binary search of 1,000 elements would be, on average, 50× faster than a sequential search. A sequential search checks each element of an array list until a matching element is found. The process can be represented with the equation S(n) = n ∕ 2, where n represents the number of elements in the array list and S(n) represents the average number of sequential comparisons it will take. Thus, an array of 1,000 elements would take, on average, 500 comparisons to target. A binary search sorts the array list in ascending order, then checks the median value of the list. If the value of the element being searched for is less than the median, then the procedure is repeated with the left half of the array; else, the procedure is repeated with the right half of the array. This process can be represented with the equation B(n) = log₂(n), where n represents the number of elements in the array list and B(n) represents the average number of binary comparisons it will take. Thus, an array of 1,000 elements would take, on average, about 10 comparisons to target. Therefore, a binary search of 1,000 elements would be, on average, 50× faster than a sequential search.
−Phoenix
−Phoenix
Tuesday, May 1, 2012
Challenge 064’s Solution
An input of “la-la-la!” will produce an output of “ala-a” in the Terminal window. The original variable str has a value of “la-la-la!” with a length of 9. First, it checks if its length is greater than or equal to 3. Next, the substring method gets the length and divides it by 3, which is 3. Thus, all elements of str that are after element 0 (inclusive) up to the third element are run through the method again via recursion. This second str has a value of “la-” and a length of 3. Running this str through the first substring method creates an str with a length less than 3, so its recursion doesn’t matter. Next, the second str is run through a substring that gets all elements after element 1 (inclusive) up to the second element and prints them on the screen. This produces an output of “a”. After this, str has its first 2 elements removed and runs again through the method; however, this str’s length is less than 3, so nothing happens. The original str, with a length of 9, now ascends to the next line of code. This str is run through a substring that gets all elements after element 3 (inclusive) up to the sixth element and prints them on the screen. This produces an output of “la-”. After this, the original str has its first 6 elements removed and runs again through the method. This third str has a value of “la!” and a length of 3. Like the second str, running this str through the first substring method creates an str with a length less than 3, so its recursion doesn’t matter. The third str is run through a substring method that gets all elements after element 1 (inclusive) up to the second element and prints them on the screen. This produces an output of “a”. Finally, str has its first 2 elements removed and runs again through the method; however, this str’s length is less than 3, so nothing happens. In total, this creates an output of “ala-a”.
−Phoenix
−Phoenix
Thursday, April 26, 2012
Challenge 063’s Solution
None of the three segments will work properly. Each segment has an int[] array a with a length of n. The int value k is equivalent to n. Each statement contains, at one point, the command “a[k] = ”. However, a starts at the 0th element, and thus, doesn’t have a kth element. This will throw an ArrayListOutOfBoundsException; thus, none of the three segments will work properly.
−Phoenix
−Phoenix
Wednesday, April 25, 2012
Challenge 062’s Solution
Of the three, only option 3 will work properly. Option 1 starts by checking if the first number is divisible by 2. If it is, the number is printed. The writeEven method is then run again. This process results in all of the even numbers in one’s set to be printed, but in ascending order; thus, option 1 doesn’t work. Option 2 again starts by checking if the first number is divisible by 2. However, the writeEven method is only repeated if the number is even, ending if it isn’t. This process will end as soon as an odd number is inputted; thus, option 2 will not work. Finally, option 3 starts immediately by repeating the writeEven method via recursion. With this, the last number is analyzed first. If this number is divisible by 2, it is printed. This process results in all of the even numbers in one’s set to be printed in descending order; thus, option 3 works.
−Phoenix
−Phoenix
Tuesday, April 17, 2012
Challenge 061’s Solution
Entering 3 into the mystery method will produce an output of 12. The method starts by assigning the int variable n as 3. It then subtracts n by both 1 and 3 using recursion until values < 0 are produced. This procedure, summarized in the figure below, creates six different negative values. It then returns each value as 2, then adds them all together. This results in the output of 12.
3
┌───┴───┐
2 0
┌─┴─┐ ┌─┴─┐
1 -1 -1 -3
┌─┴─┐
0 -2
┌─┴─┐
-1 -3
−Phoenix
3
┌───┴───┐
2 0
┌─┴─┐ ┌─┴─┐
1 -1 -1 -3
┌─┴─┐
0 -2
┌─┴─┐
-1 -3
−Phoenix
Challenge 060’s Solution
In Challenge 60, inserting a word such as “Phoenix” into the method will create an output of “xineohP”. This is mainly due to the use of the substring command. The printString method starts by accepting a String value and assigning it to the variable s. It then gets s and performs the substring method with a parameter of 1. This means that it gets s and removes the first character from the (first) word. This altered s is then resent to the printString method via recursion, and the process is repeated until s has zero elements. At that point, the s containing one element is sent through the substring method again, but this time with the parameters 0 and 1. This tells it to print the first character in s, starting at element 0, which, in this case, is the last letter of the original String s. Finally, recursion causes this procedure to repeat until the original s is sent through the last substring method, which, in effect, prints s backwards.
−Phoenix
−Phoenix
Monday, April 16, 2012
Challenge 059’s Solution
The method recur will always return the greatest int value in the list x. The program first creates an int variable t. It then checks if n, the size of x, is just 1, in which case the greatest value is the zeroth element of x. Otherwise, the method sets t as equal to the second-to-last element of x using recursion. This is repeated because of recursion until there is a t value equal to the zeroth element of x. Element 0 of x, aka t, is compared to element 1 of x. The greater of the two values is returned as the result of the last recur method, which becomes the next t. This continues until the end of the original recur method, where the greatest int value in the list x is returned.
−Phoenix
−Phoenix
Thursday, April 12, 2012
Challenge 058’s Solution
To complete Challenge 58, the following code must be placed into BlueJ™:
public class Challenge058
{
public void drawStars(int n)
{
if (n != 0)
{
for (int x = 0; x < n; x++)
System.out.print("*");
System.out.print("\n");
drawStars(n - 1);
}
else
System.out.println("No more stars for you!");
}
}
−Phoenix
public class Challenge058
{
public void drawStars(int n)
{
if (n != 0)
{
for (int x = 0; x < n; x++)
System.out.print("*");
System.out.print("\n");
drawStars(n - 1);
}
else
System.out.println("No more stars for you!");
}
}
−Phoenix
Wednesday, April 11, 2012
Challenge 057’s Solution
When the code is placed into BlueJ™, the following comes out in the Terminal window:
.
This is caused by recursion. The program starts by running the stackWords method and accepting the first word entered, being “May”. The String variable word is assigned the value of “May”. Because word isn’t equal to “.”, a second stackWords method is began before the first reaches its end. This second stackWords method has its own local variable word, equal to “the”. Again, “the” isn’t equal to “.”, and a third stackWords method is run before the second (or first) can end. This continues until the value “.” is assigned to a word variable. At this point, the seventh stackWords method is required to write the value of word in the Terminal window, then end. The program can then advance to the sixth stackWords method and do the same thing; however, the value of word for this stackWords is different from that of the seventh. Thus, the phrase “May the force be with you.” is repeated backwards. Finally, after the first stackWords method ends, the program does as well.
.
−Phoenix
.
.
you
with
be
force
the
May
.This is caused by recursion. The program starts by running the stackWords method and accepting the first word entered, being “May”. The String variable word is assigned the value of “May”. Because word isn’t equal to “.”, a second stackWords method is began before the first reaches its end. This second stackWords method has its own local variable word, equal to “the”. Again, “the” isn’t equal to “.”, and a third stackWords method is run before the second (or first) can end. This continues until the value “.” is assigned to a word variable. At this point, the seventh stackWords method is required to write the value of word in the Terminal window, then end. The program can then advance to the sixth stackWords method and do the same thing; however, the value of word for this stackWords is different from that of the seventh. Thus, the phrase “May the force be with you.” is repeated backwards. Finally, after the first stackWords method ends, the program does as well.
.
−Phoenix
Tuesday, April 3, 2012
Challenge 056’s Solution
To complete Challenge 56, the following codes must be placed into BlueJ™:
import java.util.Random;
public class Die
{
int value;
public Die()
{
int value;
}
public int roll()
{
Random rand = new Random();
return value = rand.nextInt(6) + 1;
}
public int getCurrentValue()
{
return value;
}
public int compareTo(int die1, int die2)
{
if (die1 > die2)
return 1;
if (die1 < die2)
return -1;
else
return 0;
}
}
−Phoenix
import java.util.Random;
public class Die
{
int value;
public Die()
{
int value;
}
public int roll()
{
Random rand = new Random();
return value = rand.nextInt(6) + 1;
}
public int getCurrentValue()
{
return value;
}
public int compareTo(int die1, int die2)
{
if (die1 > die2)
return 1;
if (die1 < die2)
return -1;
else
return 0;
}
}
public class DieTester
{
public static void main(String[] args)
{
Die die1 = new Die();
Die die2 = new Die();
for (int x = 1; x <= 100; x++)
{
System.out.println("Trial " + x + ":");
int roll1 = die1.roll();
System.out.println("Value of die1: " + roll1);
int roll2 = die2.roll();
System.out.println("Value of die2: " + roll2);
int compare = die1.compareTo(roll1, roll2);
System.out.println("compareTo Result: " + compare);
if (compare == 1)
System.out.println("Die 1 is larger than Die 2. \n \n");
if (compare == -1)
System.out.println("Die 1 is smaller than Die 2. \n \n");
if (compare == 0)
System.out.println("Die 1 is equal to Die 2. \n \n");
}
}
}
{
public static void main(String[] args)
{
Die die1 = new Die();
Die die2 = new Die();
for (int x = 1; x <= 100; x++)
{
System.out.println("Trial " + x + ":");
int roll1 = die1.roll();
System.out.println("Value of die1: " + roll1);
int roll2 = die2.roll();
System.out.println("Value of die2: " + roll2);
int compare = die1.compareTo(roll1, roll2);
System.out.println("compareTo Result: " + compare);
if (compare == 1)
System.out.println("Die 1 is larger than Die 2. \n \n");
if (compare == -1)
System.out.println("Die 1 is smaller than Die 2. \n \n");
if (compare == 0)
System.out.println("Die 1 is equal to Die 2. \n \n");
}
}
}
−Phoenix
Friday, March 16, 2012
Challenge 055’s Solution
All three statements will successfully transfer money from one account to the other. Statement I removes $50 from the BankAccount object b and transfers it to the SavingsAccount object timsSavings, leaving b with $600 and s with $1,550. Statement II removes $30 from timsSavings and transfers it to the CheckingAccount object daynasChecking, leaving timsSavings with $1,470 and daynasChecking with $2,030. Finally, statement III removes $55 from daynasChecking and transfers it to b, leaving daynasChecking with $1,970 and b with $705.
−Phoenix
−Phoenix
Challenge 054’s Solution
Of the five statements, only statement C avoids causing a ClassCastException. This is because of the casting present in each statement. The program first creates three objects: the BankAccount object b, the SavingsAccount object s, and the CheckingAccount object c. Statement A attempts to cast b into a SavingsAccount object, but they are not compatible, so statement A is false. Statement B attempts to cast b into a CheckingAccount object, but they are also not compatible, so statement B is false. Statement C attempts to recast c into a CheckingAccount object, then tells it to perform the deposit method. This is entirely valid, so statement C is true. Statement D attempts to cast s into a CheckingAccount object, but they are not compatible, so statement D is false. Finally, statement E attempts to cast c into a SavingsAccount object, but, again, they are not compatible, so statement E is false.
−Phoenix
−Phoenix
Tuesday, March 13, 2012
Challenge 052’s Solution
Of the five commentators, all five are correct. The first post, written by Dave Dee, claims that the interface class SmartPlayer automatically implements Player’s interface. SmartPlayer inherits all of HumanPlayer’s methods. These methods are implemented from Player, so the statement is true. The second post, written by Dozey, claims that HumanPlayer must implement all of Player’s methods to work. This is true: interfaces, when implemented, should have every method specifically defined within the class that inherits it. The third post, written by Beaky, claims that referencing an object of type Player is not possible. This is true, as interface classes do not have constructors; thus, they cannot be referenced as object types. The fourth post, written by Mick, claims that SmartPlayer can override the defined methods of HumanPlayer. This is true as well, as a subclass is able to override the methods of its superclass. Finally, the fifth post, written by Tich, claims that a client program method can require a parameter of type Player. While this can be required, the usability of the method is questionable, as Player constructors cannot successfully be formed. Thus, on account to technicality, Tich is correct.
−Phoenix
−Phoenix
Monday, March 12, 2012
Challenge 053’s Solution
To complete Challenge 53, the following code must be pasted into BlueJ™:
public class FlyingOstrich implements FlyingObject
{
public void fly()
{
System.out.println("The ostrich gets a running start.");
System.out.println("It starts to flap its wings.");
System.out.println("The ostrich picks up its speed…");
if (!isFlying())
{
System.out.println("…and nothing happens.");
}
else
{
System.out.println("…and runs onto an airplane.");
}
System.out.println("\nOSTRICHES CANNOT FLY!");
}
public boolean isFlying()
{
return false;
}
}
−Phoenix
public class FlyingOstrich implements FlyingObject
{
public void fly()
{
System.out.println("The ostrich gets a running start.");
System.out.println("It starts to flap its wings.");
System.out.println("The ostrich picks up its speed…");
if (!isFlying())
{
System.out.println("…and nothing happens.");
}
else
{
System.out.println("…and runs onto an airplane.");
}
System.out.println("\nOSTRICHES CANNOT FLY!");
}
public boolean isFlying()
{
return false;
}
}
−Phoenix
Friday, March 9, 2012
Challenge 051’s Solution
In Part I of Challenge 51, all four concepts can be seen in the code sample. First, method overriding is seen with method1. This method is originally defined in ClassA, then redefined in ClassB. ClassB will run its own version of method1 instead of the version inherited from ClassA, making method1 an example of method overriding. Next, method overloading is seen with methodB. ClassA has two methodBs: one lacking parameters, and one requiring an int value n. They both have the same name, but are two different methods, making methodB an example of method overloading. After that, information hiding is seen in the int variable var1. This variable has been declared private, so it cannot be directly referred to outside of ClassB. Because of its private status, var1 is an example of information hiding. Finally, procedural abstraction is seen with method3. Procedural abstraction is the use of multiple methods to perform a function. methodA is given an int value n from method3, performs a calculation, then returns the value back to method3, which makes method3 an example of procedural abstraction.
In Part II of Challenge 51, only statement III has a chance of working. To understand why, one first has to analyze the declarations of ob1 and ob2. ob1 is a no-args ClassA object created by the ClassA class, so it can perform all of ClassA’s methods. ob2, while declared as a ClassB object, is created by the ClassA class. This limits ob2 to performing only ClassA’s methods. Statement I has ob1 perform the method2 method. However, method2 can only be performed by ClassB objects, so statement I cannot be performed. Similarly, statement II has ob2 perform the method2 method. ob2 is, like ob1, a ClassA object, so method2 cannot be performed, making statement II false as well. Finally, statement III makes ob1 a ClassB object, then has it perform the method2 method. Because it converts ob1 before asking it to perform method2, statement III can be performed, making it true.
−Phoenix
In Part II of Challenge 51, only statement III has a chance of working. To understand why, one first has to analyze the declarations of ob1 and ob2. ob1 is a no-args ClassA object created by the ClassA class, so it can perform all of ClassA’s methods. ob2, while declared as a ClassB object, is created by the ClassA class. This limits ob2 to performing only ClassA’s methods. Statement I has ob1 perform the method2 method. However, method2 can only be performed by ClassB objects, so statement I cannot be performed. Similarly, statement II has ob2 perform the method2 method. ob2 is, like ob1, a ClassA object, so method2 cannot be performed, making statement II false as well. Finally, statement III makes ob1 a ClassB object, then has it perform the method2 method. Because it converts ob1 before asking it to perform method2, statement III can be performed, making it true.
−Phoenix
Thursday, March 8, 2012
Challenge 050’s Solution
Of the three, only statement II is true. Statement I states that Teacher will inherit Person’s constructors. However, subclasses do not inherit its superclasses’ constructors; thus, statement I is false. Statement II states that Teacher can create methods and instance variables other than those provided by Person. This is true, as subclasses can create its own methods and instance variables—be they public or private. Finally, statement III states that Teacher can override Person’s private constructors. However, these are private—they cannot be accessed outside of Person. Thus, statement III is false.
−Phoenix
−Phoenix
Thursday, March 1, 2012
Challenge 049’s Solution
To complete Challenge 49, the following codes must be placed into BlueJ™:
import java.lang.Math;
public class Circle extends Shape
{
private double radius;
public Circle(String name, double r)
{
super(name);
radius = r;
}
public double area()
{
return (Math.PI * radius * radius);
}
public double perimeter()
{
return (2 * radius * Math.PI);
}
}
public class Square extends Shape
{
private double length;
public Square(String name, double ℓ)
{
super(name);
length = ℓ;
}
public double area()
{
return (length * length);
}
public double perimeter()
{
return (length * 4);
}
}
−Phoenix
import java.lang.Math;
public class Circle extends Shape
{
private double radius;
public Circle(String name, double r)
{
super(name);
radius = r;
}
public double area()
{
return (Math.PI * radius * radius);
}
public double perimeter()
{
return (2 * radius * Math.PI);
}
}
public class Square extends Shape
{
private double length;
public Square(String name, double ℓ)
{
super(name);
length = ℓ;
}
public double area()
{
return (length * length);
}
public double perimeter()
{
return (length * 4);
}
}
−Phoenix
Challenge 048’s Solution
Of the three, only statements II and III are true. This is because of the difference between the == operator and the equals method. First, all three constructors successfully create String objects called s1, s2, and s3 that represent the string "crab". Next are the three statements. Statement I is true if “s1 == s2”. Both s1 and s2 equal the String value "crab"; however, the == operator doesn’t compare the values of s1 and s2, rather their addresses. Basically, it sees whether or not the two references are to the same object. s1 and s2 are two different objects; thus, the statement “s1 == s2” is false. Statement II is true if “s1.equals(s2)”. The equals method compares the values of s1 and s2. Both s1 and s2 equal the String value "crab"; thus, the statement “s1.equals(s2)” is true. Finally, statement III is true if “s3.equals(s2)”. Both s3 and s2 equal the String value "crab"; thus, the statement “s3.equals(s2)” is true.
−Phoenix
−Phoenix
Tuesday, February 21, 2012
Challenge 047’s Solution
The single statement that generates the random number object winner is:
int winner = new Random().nextInt(49) + 1;
−Phoenix
int winner = new Random().nextInt(49) + 1;
−Phoenix
Challenge 046’s Solution
To complete Challenge 46, the following code must be placed into BlueJ™:
import java.lang.Double;
import java.lang.Math;
public class Challenge046
{
public Double squareRoot(Double d)
{
// Pre-condition: d ≥ 0
// Post-condition: returns a Double value equal to √d
double doubD = Double.valueOf(d);
double sqrtD = Math.sqrt(doubD);
return sqrtD;
}
}
−Phoenix
import java.lang.Double;
import java.lang.Math;
public class Challenge046
{
public Double squareRoot(Double d)
{
// Pre-condition: d ≥ 0
// Post-condition: returns a Double value equal to √d
double doubD = Double.valueOf(d);
double sqrtD = Math.sqrt(doubD);
return sqrtD;
}
}
−Phoenix
Tuesday, February 14, 2012
Challenge 045’s Solution
To complete Challenge 45, the following code must be placed into BlueJ™:
import info.gridworld.actor.Actor;
import info.gridworld.actor.Rock;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
public class RollingStone extends Rock
{
public RollingStone()
{
super();
setDirection(270);
}
public void act()
{
if (canMove())
move();
else
turn();
}
public void turn()
{
setDirection(getDirection() + Location.HALF_CIRCLE);
}
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
Actor neighbor = gr.get(next);
if (neighbor != null)
neighbor.removeSelfFromGrid();
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public boolean canMove()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return false;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
return false;
Actor neighbor = gr.get(next);
return true;
}
}
−Phoenix
import info.gridworld.actor.Actor;
import info.gridworld.actor.Rock;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
public class RollingStone extends Rock
{
public RollingStone()
{
super();
setDirection(270);
}
public void act()
{
if (canMove())
move();
else
turn();
}
public void turn()
{
setDirection(getDirection() + Location.HALF_CIRCLE);
}
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
Actor neighbor = gr.get(next);
if (neighbor != null)
neighbor.removeSelfFromGrid();
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public boolean canMove()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return false;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
return false;
Actor neighbor = gr.get(next);
return true;
}
}
−Phoenix
Tuesday, February 7, 2012
Challenge 044’s Solution
The code in Challenge 44 can be rewritten using a for loop in the following way:
int sum = 0;
for (int index = 0; index < arr.length; index++)
{
sum += arr[index];
}
It can also be rewritten using a for-each loop in the following way:
.
−Phoenix
int sum = 0;
for (int index = 0; index < arr.length; index++)
{
sum += arr[index];
}
It can also be rewritten using a for-each loop in the following way:
.
int sum = 0;
for (int index : arr)
{
sum += index;
}
for (int index : arr)
{
sum += index;
}
Monday, February 6, 2012
Challenge 043’s Solution
The “for each” loop is used to determine the values of sum1 and sum2. These loops are used for arrays such as the int[] array named arr. The loop creates an int variable named num. Each time the loop runs, num is equal to the next element in the arr array. If num is either positive or odd, then the element value num is added to the total value of sum1. Otherwise, if num is negative and even, then the element value num is added to the total value of sum2. The loop processes every value of the arr array through num. Therefore, the sum1 value output represents the sum of all positive or odd numbers in the arr list, while the sum2 value output represents the sum of all negative and even numbers in the arr list.
−Phoenix
PS: In line 10 of your code, you mistakenly wrote “sum += num;” instead of “sum1 += num;”.
−Phoenix
PS: In line 10 of your code, you mistakenly wrote “sum += num;” instead of “sum1 += num;”.
Thursday, February 2, 2012
Challenge 042’s Solution
To complete Challenge 42, the following code must be placed into BlueJ™:
−Phoenix
import java.util.Arrays;
public class Challenge042
{
public static void main(String[] args)
{
int[] scores = {97,56,78,88};
Arrays.sort(scores);
System.out.println("Original Scores:");
for(int x = 0; x <= scores.length - 1; x++)
{
System.out.println(scores[x]);
}
System.out.println();
curveScores(scores);
}
public static void curveScores(int[] s)
{
int[] sortedScores = s;
Arrays.sort(sortedScores);
int curve = 100 - sortedScores[sortedScores.length - 1];
System.out.println("Curved Scores:");
for(int x = 0; x <= s.length - 1; x++)
{
System.out.println((s[x] + curve));
}
}
}
public class Challenge042
{
public static void main(String[] args)
{
int[] scores = {97,56,78,88};
Arrays.sort(scores);
System.out.println("Original Scores:");
for(int x = 0; x <= scores.length - 1; x++)
{
System.out.println(scores[x]);
}
System.out.println();
curveScores(scores);
}
public static void curveScores(int[] s)
{
int[] sortedScores = s;
Arrays.sort(sortedScores);
int curve = 100 - sortedScores[sortedScores.length - 1];
System.out.println("Curved Scores:");
for(int x = 0; x <= s.length - 1; x++)
{
System.out.println((s[x] + curve));
}
}
}
−Phoenix
Wednesday, February 1, 2012
Challenge 041’s Solution
To complete Challenge 41, the following codes must be placed into BlueJ™:
public class BankAccount
{
public double balance;
public BankAccount()
{
}
public BankAccount(double b)
{
balance = b;
}
public double makeDeposit(double d)
{
System.out.println("You’ve deposited $" + d + ". \nYour current balance is $" + (balance + d) + ".");
return balance += d;
}
public double makeWithdraw(double w)
{
if (w <= balance)
{
System.out.println("You’ve withdrawn $" + w + ". \nYour current balance is $" + (balance - w) + ".");
return balance -= w;
}
else
{
System.out.println("ERROR: You cannot withdraw $" + w + "! \nYour current balance is $" + balance + ".");
return balance;
}
}
public double getBalance()
{
System.out.println("Your current balance is $" + balance + ".");
return balance;
}
}
−Phoenix
public class BankAccount
{
public double balance;
public BankAccount()
{
}
public BankAccount(double b)
{
balance = b;
}
public double makeDeposit(double d)
{
System.out.println("You’ve deposited $" + d + ". \nYour current balance is $" + (balance + d) + ".");
return balance += d;
}
public double makeWithdraw(double w)
{
if (w <= balance)
{
System.out.println("You’ve withdrawn $" + w + ". \nYour current balance is $" + (balance - w) + ".");
return balance -= w;
}
else
{
System.out.println("ERROR: You cannot withdraw $" + w + "! \nYour current balance is $" + balance + ".");
return balance;
}
}
public double getBalance()
{
System.out.println("Your current balance is $" + balance + ".");
return balance;
}
}
public class SavingsAccount extends BankAccount
{
public double interest;
public SavingsAccount()
{
}
public SavingsAccount(double balance, double i)
{
super(balance);
interest = i;
}
public double addInterest()
{
return balance += balance * interest;
}
}
{
public double interest;
public SavingsAccount()
{
}
public SavingsAccount(double balance, double i)
{
super(balance);
interest = i;
}
public double addInterest()
{
return balance += balance * interest;
}
}
public class CheckingAccount extends BankAccount
{
public double minBalance;
public double fee;
public CheckingAccount()
{
}
public CheckingAccount(double balance)
{
super(balance);
minBalance = 50.0;
fee = 2.0;
}
public double makeWithdraw(double w)
{
if (w <= balance)
{
if (balance - w < 50.)
{
System.out.println("You’ve withdrawn $" + w + ", and have been charged $2.00. \nYour current balance is $" + (balance - (w + 2.)) + ".");
return balance -= w + 2.;
}
else
{
System.out.println("You’ve withdrawn $" + w + ". \nYour current balance is $" + (balance - w) + ".");
return balance -= w;
}
}
else
{
System.out.println("ERROR: You cannot withdraw $" + w + "! \nYour current balance is $" + balance + ".");
return balance;
}
}
}
{
public double minBalance;
public double fee;
public CheckingAccount()
{
}
public CheckingAccount(double balance)
{
super(balance);
minBalance = 50.0;
fee = 2.0;
}
public double makeWithdraw(double w)
{
if (w <= balance)
{
if (balance - w < 50.)
{
System.out.println("You’ve withdrawn $" + w + ", and have been charged $2.00. \nYour current balance is $" + (balance - (w + 2.)) + ".");
return balance -= w + 2.;
}
else
{
System.out.println("You’ve withdrawn $" + w + ". \nYour current balance is $" + (balance - w) + ".");
return balance -= w;
}
}
else
{
System.out.println("ERROR: You cannot withdraw $" + w + "! \nYour current balance is $" + balance + ".");
return balance;
}
}
}
−Phoenix
Thursday, January 26, 2012
Challenge 040’s Solution
Of the three, only statements 1 and 3 are valid. This is because of how the classes are written. The Dancer class contains the leap() method. The BalletDancer class is an extension of the Dancer class; thus, the BalletDancer class can be used to create Dancer objects and perform Dancer methods. However, the Dancer class cannot be used to create BalletDancer objects or perform BalletDancer-specific methods, like the glide() method. Object b is from the BalletDancer class—it can perform both the leap() method and the glide() method—so statement 1 is valid. However, object d is from the Dancer class—it can perform the leap() method, but not the glide() method—so statement 3 is valid, while statement 2 is invalid.
−Phoenix
−Phoenix
Wednesday, January 25, 2012
Challenge 039’s Solution
Of the three, only option II will correctly implement code for the constructor of the Hen class. First, the Bird class is the superclass of Hen; thus, a Hen object must inherit the parameters of a Bird object. To do this, one must use the statement “super()” as the first statement in the Hen constructor. This immediately eliminates option III, which lacks the super() statement. Next, the super() statement looks in the Bird class for a constructor that takes the parameters listed within its parenthesis. Option I simply states “super();”, so Java™ will look in the Bird class for a no-args constructor. However, Bird doesn’t contain a no-args constructor, so option I is eliminated. On the other hand, option II states “super(species);”, so Java™ will look in the Bird class for a constructor containing the parameter species. The constructor Bird contains this; thus, only option II correctly implements code for the constructor of the Hen class.
−Phoenix
PS: Line 9 of the Owl code mistakenly says “Systme” instead of “System”.
PPS: Line 8 of the Hen code is missing a “"”.
−Phoenix
PS: Line 9 of the Owl code mistakenly says “Systme” instead of “System”.
PPS: Line 8 of the Hen code is missing a “"”.
Challenge 038’s Solution
To answer the Free Response Question #1, one can write the following code:
/**
* Postcondition: Prints all notes in noteList, one per line.
* Notes are numbered 1, 2, ...
* Each number is followed by a period and a space.
*/
public void printNotes()
{
for(int n = 0; n <= noteList.size() - 1; n++)
{
System.out.println(n + 1 + ". " + noteList.get(n).toString());
}
}
To answer the Free Response Question #2, one can (again) write the following code:
public class PartTimeEmployee extends Employee
{
private double workFraction;
private boolean isUnionMember;
public PartTimeEmployee(String name, String city, boolean isCitizen, double salary, double work, boolean isMember)
{
super(name, city, isCitizen, salary);
workFraction = work;
if(salary > 15000)
{
isMember = false;
}
else
{
isMember = true;
}
}
public double getWork()
{
return workFraction;
}
public boolean getMemberStatus()
{
return isUnionMember;
}
}
−Phoenix
/**
* Postcondition: Prints all notes in noteList, one per line.
* Notes are numbered 1, 2, ...
* Each number is followed by a period and a space.
*/
public void printNotes()
{
for(int n = 0; n <= noteList.size() - 1; n++)
{
System.out.println(n + 1 + ". " + noteList.get(n).toString());
}
}
To answer the Free Response Question #2, one can (again) write the following code:
public class PartTimeEmployee extends Employee
{
private double workFraction;
private boolean isUnionMember;
public PartTimeEmployee(String name, String city, boolean isCitizen, double salary, double work, boolean isMember)
{
super(name, city, isCitizen, salary);
workFraction = work;
if(salary > 15000)
{
isMember = false;
}
else
{
isMember = true;
}
}
public double getWork()
{
return workFraction;
}
public boolean getMemberStatus()
{
return isUnionMember;
}
}
−Phoenix
Subscribe to:
Posts (Atom)