CS 312 - Exam 2 Practice Solutions

1. Write a do-while loop that prints random numbers between 0 and 99 (inclusive) until a number greater than 50 is printed.

Random r = new Random();
do {
int n = r.nextInt(100);
System.out.println(n);
} while(n <= 50);

2. Consider the following method:
public static void mystery(int x, int y) {
int z = 0;
// Point A

while(x != y) {
// Point B
z++;
// Point C
if(x > y) {
// Point D
x = x/10;
}
else {
// Point E
y = y/10;
}
// Point F
} // end while
// Point G
}

Consider the assertions x > y, x == y, z == 0. For each labeled point of execution, determine if the assertion is: ALWAYS, SOMETIMES, or NEVER true.

x > y                      x == y                   z == 0
----------------------------------------------------------------------------------------------------------------------------------------
Point A                        Sometimes             Sometimes            Always

Point B                        Sometimes             Never                    Sometimes

Point C                        Sometimes             Never                    Never

Point D                        Always                  Never                    Never

Point E                        Never                     Never                    Never

Point F                        Sometimes             Sometimes            Never

Point G                       Never                     Always                  Sometimes

3. What is the output?
String word = "a";
do {
word = "b" + word + "b";
} while (word.length() < 10);
System.out.println(word);

Output:
bbbbbabbbbb

4. What is the output?
System.out.printf("Name:%10s, Score:%6d", "Rich", 95);

Output:
Name:       Rich, Score:    95