int n = 4, p = 1;
while (n > 0) {
p *= n;
n--;
System.out.println(p);
}
Rewrite the following while loop as a for loop.
int value = 10;
while (value < 1000) {
System.out.println(value);
value *= 2;
}
Suppose you have been given the Die class described in lectures.
Recall that the
Die class has the following methods: roll,
getNumberOfSides, and
getNumberOfRolls.
Write a code segment rolls two 6-sided dice 20 times and displays the sum
of the two dice for
each roll.
Write a code segment that rolls two 6-sided dice until either a 2 or a 12
is obtained. The sum
of each roll should be displayed, and the total number of rolls it took
should be displayed at the
end.
Write a code segment that rolls a single 8-sided die repeatedly, until
the sum of its roll
values exceed 100. The number of rolls required should be displayed at the
end.
Consider the following static method.
public static String mystery(String str1, String str2)
{
String copy = "";
int index = 0;
while (index < str1.length() && index < str2.length()) {
copy += str1.charAt(index) + str2.charAt(index);
index++;
}
return copy;
}
What would be returned by each of the following method calls?
mystery("foo", "bar")
mystery("foo", "barbaloot")
mystery("fooboo", "bar")
mystery("", "bar")
Describe in concise English the purpose of the following method. That
is, when called with an
aribtrary ArrayList of words, what does the method do?
public void doSomething(ArrayList words)
{
for (int i = words.size()-1; i >= 0; i--) {
String entry = words.get(i);
System.out.println(entry);
}
}
Complete the definition of the numOccurrences method below,
which takes an
ArrayList of words and a desired word, and returns the number of
times the desired word
appears in the ArrayList.
public static int numOccurrences(ArrayList words, String desired)
{
}