Chapter 5: Booleans and Flow Control

The exercises here are taken from my book, The Java Developer's Resource.

Quiz

1. Is a float large enough to count the king's wheat?

Yes.

2. Why isn't there a ** or a // operator?

Multiplying or dividing by one doesn't change the number. The following loops are infinite.

int i = 1;
while (i** < 2) {
...
}

while (i // > 0) {
...
}

You may also note that // starts a one line comment (Though it wouldn't if there were a need for a real // operator).

3. Given that a is a boolean variable, what's the value of (a || !a)?

According to classical, Aristotelian logic and to Java (a || !a) is always true.

4. Here's one that stumped the author until he got some help from comp.lang.java. What's wrong with this program?
public class BytePrint {

public void main(String[] args) {
for (byte b = -128; b <= 127; b++) {
System.out.println(b);
}

}

}
The <= should be <. Otherwise one is added to 127, which produces 128. However 128 is too large to fit in a byte so it wraps around to -128 which starts the loop over. That is, this is an infinite loop. You can also fix the problem by making b an int.

Exercises

1. Write the FahrToCelsius program of the last chapter using a for loop instead of a while loop.

// Print a Fahrenheit to Celsius table

class FahrToCelsius  {

public static void main (String args[]) {

double fahr, celsius;

for (fahr = 0.0; fahr <= upper; fahr += 20.0) {
celsius = (5.0 / 9.0) * (fahr-32.0);
System.out.println(fahr + " " + celsius);
}

}

}
2. Write the combination lock programs of Chapter 3 using for loops.

class lock {

public static void main(String[] args)  {

for (int i = 0; i <= 36; i++) {
for ( int j = 0; j <= 36; j++) {
for  (int k = 0; k <= 36; k++) {
System.out.println(i + " " + j + " " + k);
}
}
}

}

}

public static void main(String[] args)  {

for (int i = 2; i <= 36; i += 3) {
for ( int j = 2; j <= 36; j += 3) {
for  (int k = 2; k <= 36; k += 3) {
System.out.println(i + " " + j + " " + k);
}
}
}

}

}

[ Exercises | Cafe Au Lait | Books | Trade Shows | Links | FAQ | Tutorial | User Groups ]