CHAPTER 7
Typically, computers execute code one line at a time from top to bottom. Control structures allow us to specify other orders of execution, such as branching on conditions and repeating loops of code. In Java, the available control structures are if statements, for loops, while loops, do while loops, switch statements, for each loops, and try/catch blocks.
If statements allow us to execute a block of code when a particular condition is true, otherwise the code block is skipped. The basic syntax to an if statement is listed in Code Listing 7.0.
Code Listing 7.0: Basic If Statements
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int height = 0; System.out.print("How tall are you (in cm)? "); height = Integer.parseInt(scanner.nextLine());
if(height < 100) { System.out.println("Wow! Are you a quokka?"); }
if(height > 300) System.out.println("Yeah right? Are you a giraffe?");
} } |
Code Listing 7.0 shows two if statements. First, the listing shows a prompt to users asking for their height. The height variable’s value is read as a string, using the scanner and parsed to an int with the Integer.parseInt method (parsing integers is not our primary focus, but this is an example of how it is done). The if statements begin with the if keyword and are followed by a boolean expression in brackets: (height < 100) in the first if statement, and (height > 300) in the second if statement (remember the relational operators < and > always return a boolean value). When the program evaluates the expressions, they will either be true statements or they will be false. When the statement evaluates to true, the code blocks following the if statement are executed. When the expression evaluates to false, the code block is skipped and the program will resume executing code after the if statement’s code block.
If we run the code from Code Listing 7.0 and input a height of 20, the program will respond with Wow! Are you a quokka?. Running the program again, we could input a height of 500, and the program would output Yeah right? Are you a giraffe?. Note that if the input is greater than or equal to 100 and also less than or equal to 300, no output will be displayed.
When our code block consists of a single line of code (as in both of the examples from Code Listing 7.0), the curly brackets are optional. This is why the second if statement in Code Listing 7.0 is missing the curly brackets.
Combining several conditions together into logical expressions is often convenient. This is exactly what the Boolean operators ||, &&, and ! are used for. When we use || between two or more statements, any true statement will cause the entire expression to be true.
Code Listing 7.1: Using Boolean OR
int password = 25; String userName = "Sam"; if(password == 10 || userName == "Sam") { System.out.println("That is the correct password or User Name!"); } |
In Code Listing 7.1, the expression in the if statement is true if password is 10 or if the userName is Sam. This is Boolean OR, so the if statement is also true when both of these conditions are true (unlike English “or,” in which “apples or oranges” means one or the other but not both). The logical OR operator combines the two statements password==10, and userName==“Sam” into a single boolean value. The operator returns true if either of the conditions is true or if they both are true. Typically, when we check a user name and password, we need both of them to be correct, so Boolean OR is probably not a good choice in this particular circumstance. Code Listing 7.2 shows the use of Boolean AND.
Code Listing 7.2: Using Boolean AND
int password = 25; String userName = "Sam"; if(password == 10 && userName == "Sam") { System.out.println("That is the correct password AND User Name!"); } |
The && operator combines two Boolean statements, and both must be true or the operator will return false. In the code, if the password is 10 and the userName is set to Sam, then the System.out.println will be executed. The password in the code is set to 25, so the println will not execute. However, if you change the password to 10, the println will execute because both conditions for the && operator are true.
If you want to check multiple possible conditions using the same variable, remember to use the variable name twice:
if(age == 50 || 60) { … // This is incorrect!
if(age == 50 || age == 60) { … // This is correct!
The first example reads perfectly normally: If age is 50 or 60 …. However, this is not correct Java code. The computer will read the condition “age == 50”. This expression evaluates to false. Due to the || operator, the program will look for the next condition. The next condition consists of the integer literal 60 by itself. But 60 is not a condition, and the program will not run. The correct way to check multiple settings for the age variable is illustrated in the second example—we include “age == 60” instead of 60 by itself.
We can place if statements inside the code blocks of other if statements. These are called nesting if statements.
Code Listing 7.3: Nested If Statements
int age = 190, price = 14; if(age > 50 && age < 100) { if(price > 20) { System.out.println("Age: " + age + " Price: " + price); } } |
Code Listing 7.3 contains a nested if statement. The first condition tests the variable “age” and determines if it is in the range of 50 to 100 (not inclusive). Due to the && operator, both conditions must be true. Therefore, if age is in the range from 51 to 99, the if statement's code block will execute. The inner if statement tests whether or not the price is greater than 20. This means that if the age does not fall within the range of 51 to 99, the computer will not consider the second if statement because it exists in the code block of the first.
We can follow an if statement with any number of else if (which translates into “otherwise”) statements. And we can end a set of if/else if with a final else statement. Only one code block in a set of if/else if/else will execute. The code block that executes will always be the first block in which the condition evaluates to true.
If the condition of an if or an else if evaluates to false, the program will look for the next else if or else. When one of the conditions is found to be true, the computer will execute the associated code block for that particular condition, then it will drop down below the entire if/else if/else block and resume execution after the set of conditions. We use else if to provide additional conditions. The else if keyword is followed by a condition in brackets—exactly the same as an if statement. The difference is that an else if must have an if statement before it. The else if cannot stand alone.
The else keyword is always the final option. When the computer reads an else block, if none of the previous conditions evaluated to true, the else block will always execute. The else block is always placed at the end, and it does not have a condition.
Code Listing 7.4: If / Else If / Else Blocks
int i = 25; if(i % 2 == 0) { System.out.println("i is even"); } else if(i % 3 == 0) { System.out.println("i is odd, but divisible by 3"); } else if(i % 5 == 0) { System.out.println("i is divisible by 5"); } else { System.out.println("i is not divisible by 2, 3, or 5"); } |
Code Listing 7.4 shows a simple series of if/ else if/else. Only one of the conditions will have its code executed. The computer will check the if and else if from top to bottom. The variable i is set to 25, which is an odd number but is divisible by 5. Therefore, the second else if will print “i is divisible by 5”. No other blocks will execute after this.
If, instead of 25, we set the variable i to 22, the first code block will execute and the program will print “i is even” to the screen. And, if we set the variable i to 17, note that 17 is not even, so the first condition fails. And 17 is not divisible by 3, so the second condition fails. And 17 is not divisible by 5, so the third condition fails. At this point the program encounters the else. The else block will always execute if the program encounters it, so with i set to 17, the program will print “i is not divisible by 2, 3, or 5” to the screen.
For loops allow us to execute a block of code a specified number of times. We often use a counter and execute the code until the counter reaches some value. This allows us to execute a code block a specific number of times. The syntax is as follows:
for ([init]; [condition]; [increment] ) {
// Body of the loop
}
for([init]; [condition]; [increment])
// Some single statement!
If the body of the for loop has a single statement, we do not need the curly braces.
Init: The initialization is where we declare the counter variable and set its initial value.
Condition: The condition is a Boolean expression, just like an if statement. The code block of the for loop will repeat until the condition evaluates to true.
Increment: The increment section allows us to increment or decrement our counter.
Code Listing 7.5: For Loop Counting from 0 to 9
for(int j = 0; j < 10; j++) { System.out.println(j); } |
Code Listing 7.5 shows a for loop that iterates 10 times and counts from 0 to 9. The initialization step of this loop declares and defines an integer variable called j, setting its initial value to 0. The condition is “j < 10”, meaning “while j is less than 10.” The increment is “j++”, which means “every time the loop's body is executed, the j integer will count up.” After executing the loop body 10 times, the j integer will increment to 10 and the condition “j < 10” will evaluate to false. The loop will terminate, and the program will continue to execute the code following the loop.
Note: Code Listing 7.5 shows a very common method for instructing the computer to loop 10 times. But notice that although the loop body is executed 10 times, the program counts from 0 to 9, not from 1 to 10. If you need your for loop to count as a human does, from 1 to 10, use something like the following instead: for(int j = 1; j <= 10; j++).
Code Listing 7.6: Counting Backwards with a For Loop
for(int j = 10; j > 0; j--) { System.out.println(j); } |
The for loop in Code Listing 7.6 counts backward beginning from 10 and counting to 1. It could be read “for j is 10, while j is greater than 0, decrement j”. This is like a loop that counts up, but the “increment” part of the loop has “j--”, which will cause the variable j to count downwards. Also, note that the starting value and the condition are switched—we start at 10 and loop while j is greater than 1.
Note: There is a special type of for loop used to iterate over the items in a collection, such as an array. The loop is commonly called a for each loop. For more information on the for each loop, visit http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html.
We can place a for loop in the body of another for loop. This is useful for traversing multidimensional arrays.
Code Listing 7.7: Nested For Loops
for(int outerCounter = 0; outerCounter < 5; outerCounter++) { for(int innerCounter = 0; innerCounter < 3; innerCounter++) { System.out.println("Outer Counter: " + outerCounter + " Inner Counter: " + innerCounter); } } |
Code Listing 7.7 shows nested for loops. The outer counter counts from 0 up to and including 4. In the body of the outer loop, the inner loop counts from 0 up to and including 2. The outer loop will execute five times, and each time it executes, the inner loop will execute three times. Therefore, the body of the inner loop will execute a total of 3*5 times, or 15. The output of this code is as follows:
Outer Counter: 0 Inner Counter: 0
Outer Counter: 0 Inner Counter: 1
Outer Counter: 0 Inner Counter: 2
Outer Counter: 1 Inner Counter: 0
...
Outer Counter: 3 Inner Counter: 2
Outer Counter: 4 Inner Counter: 0
Outer Counter: 4 Inner Counter: 1
Outer Counter: 4 Inner Counter: 2
Notice that the outerCounter remains the same for exactly three iterations of the inner loop. Then it counts up one. Each time the outerCounter counts up one, the innerCounter counts 0, then 1, then 2. You can nest for loops arbitrarily deep. We could have another for loop in the body of the inner loop in Code Listing 7.7 and another loop in the body of that one.
The break keyword is used in the body of several control structures (for, while, do while, and switch as well). It causes the program to immediately jump to the next statement outside the body of the control structure. This is useful for stopping infinite loops (such as while(true), which typically would never terminate) and for terminating the loop early.
The continue keyword is used to jump to the top of the loop. It is useful when you do not want the remainder of the loop’s body to execute during some particular iteration.
Break and continue always operate on the innermost loop when loops are nested.
There are two types of while loop—the while loop itself and the do while loop. The only difference is that the do while loop checks the condition after executing the body and is therefore guaranteed to run the loop’s body at least once. Whereas the while loop checks the condition before running the body of the loop and, if the condition is false to begin with, the body of the loop will not execute at all. Code Listing 7.8 shows the basic syntax for these loops.
Code Listing 7.8: Nested For Loops
while(condition) { // Body of the loop } do { // Body of the loop } while(condition); |
The condition can be any boolean statement (i.e. any logical expression that results in a boolean value). The loop will continue to execute while the condition evaluates to true. When the condition becomes false, the loop terminates.
Code Listing 7.9: While and Do While Loops
int counter = 0; while(counter < 10) { System.out.println("Counter in while: " + counter); counter++; } do { System.out.println("Counter in do ... while: " + counter); counter++; } while(counter < 10); |
Code Listing 7.9 shows an example of using a while and a do while loop. First, in the while loop, the counter variable will increment from 0 to 9. When the counter variable reaches 10, the condition of the while loop will fail. This particular while loop is very similar to a for loop, and in fact there is no while loop that could not also be written as a for loop and vice versa.
The do while loop has the same condition as the while loop. After the program executes the while loop, it will increment the counter variable to 10. The do while loop’s condition is false (counter is not less than 10). But the do while loop will still execute its body once before terminating the loop because it checks the condition at the end.
A switch statement is simply another way of coding a collection of if statements. In order to convert a collection of if statements into a switch, the conditions in the if and the else if statements must all address the same variable. In the following example code (Code Listing 7.10), all of the conditions address the variable i, therefore this series of if statements can be converted to a switch. The following shows a comparison of a collection of if/else and a switch statement that will do exactly the same thing (note that the switch example is not actually code and will not run).
Code Listing 7.10: If Blocks vs. Switch
if(i == 0) // Do something else if(i == 1) // Do somethingElse else if(i == 2) // Do somethingElse else // Do the default switch (i ) { case 0: { Do something; break; } case 1: { Do somethingElse; break; } case 2: { Do SomethingElse; break; } default: { Do the default; break; } }; |
In a switch statement, we follow the switch keyword with a variable (i in the preceding example). Next, inside a code block, we provide a series of cases, each marked with the case keyword. When i matches a particular case, the code block for that case is executed.
In the switch example, each of the case's code blocks ends with the keyword break. This means that once a particular case has been executed, the program will break outside of the switch. If none of the previous cases is executed, the program will eventually find the case marked with the default keyword. The default case executes only if the previous cases did not. The default case is optional.
Tip: The break keywords in a switch are not mandatory. If you do not place a break in the cases, the program will continue and find additional cases to execute. This functionality is seldom used, and I recommend that you always use break in every case of a switch statement in order to avoid confusion when other programmers (or you) read the code.
Code Listing 7.11 shows a practical example of a switch. The listing asks the user for two numbers and a mathematical operator. It uses a switch (highlighted in yellow) to decide what to do based on the operator the user selects (note that for simplicity, the program does not try to prevent dividing by zero).
Code Listing 7.11: Calculator with Switch
import java.util.Scanner; public class MainClass { public static void main(String[] args){ Scanner s = new Scanner(System.in); // Parameters for the operation. double parameterA = 0.0, parameterB = 0.0; // Index of the operation. int operation = 0; System.out.println("Welcome to Calculator"); do { // Ask the user for two numbers and an operator: System.out.print("Type a number: "); parameterA = Double.parseDouble(s.nextLine()); System.out.print("Type another number: "); parameterB = Double.parseDouble(s.nextLine()); System.out.println("Select an option: "); System.out.println( "1. Add\n2. Subtract\n3. Multiply\n4. Divide\n0. Quit"); System.out.print(": "); operation = Integer.parseInt(s.nextLine()); // Perform the selected operation using switch. switch(operation){ case 1: { // If the user selected 1, add the parameters. System.out.println(parameterA + "+" + parameterB + "=" + (parameterA + parameterB)); break; } case 2: { // If 2, subtract the parameters. System.out.println(parameterA + "-" + parameterB + "=" + (parameterA - parameterB)); break; } case 3: { // If 3, multiply the parameters. System.out.println(parameterA + "*" + parameterB + "=" + (parameterA * parameterB)); break; } case 4: { // If 4, divide the parameters. System.out.println(parameterA + "/" + parameterB + "=" + (parameterA / parameterB)); break; } case 0: { // If 0, do nothing, they are quitting. break; } default: { // Default option prints an error message. System.out.println( "That wasn't one of the options."); } } } while(operation != 0); // The user has quit. System.out.println("Bye, bye!"); if(s != null) s.close(); } } |
When something goes wrong in our programs, the JVM will throw an exception. This means it will halt execution of the application and possibly quit with an error message. This is not optimal behavior, and the keywords try, catch, and finally offer the programmer the opportunity to preempt possible problems while handling actual problems as they arise.
An Exception is a special type of object in Java. When a problem arises in our code, the JVM will create an Exception object, complete with an error message to describe what went wrong. The Exception object will be “thrown,” which means the JVM will alert the current method that the exception has been encountered. The current method can either respond to the exception (as illustrated in Code Listing 7.12) or throw the exception again. If the current method throws the exception, the method that called it has the option of catching it and responding, and so on. If no methods respond to the exception, the program will crash and exit.
Code Listing 7.12: Try/Catch and Finally
import java.util.Scanner; import java.util.InputMismatchException; public class MainClass { public static void main(String[] args) { float numerator = 0.0f; float denominator = 0.0f; Scanner s = new Scanner(System.in); // Try to execute some code block: try { System.out.print("Enter a numerator: "); numerator = s.nextFloat(); System.out.print("Enter a denomintor: "); denominator = s.nextFloat(); if(denominator == 0.0f) throw new IllegalArgumentException(); System.out.println(numerator + " divided by " + denominator + " is equal to " + (numerator / denominator)); } // If an InputMismatchException is thrown catch (InputMismatchException e) { System.out.println("Your input was not a float."); } // If an IllegalArgumentException is thrown catch (IllegalArgumentException e) { System.out.println ("The result of division by Zero is not defined."); } // If any other type of exception is thrown catch (Exception e) { System.out.println ("An exception was thrown: " + e.getMessage()); } // After we perform try and catch: finally { if(s != null) s.close(); } System.out.println("Thank you for your time."); } } |
Code Listing 7.12 asks the user for a numerator and a denominator for a division. If the user inputs valid floats for the numerator and denominator, the program will divide the numerator by the denominator and print the results. It will then print out a thank-you message and exit.
If the user does not input valid floats for the numerator or denominator (e.g., if the user inputs a string or inputs a denominator equal to 0.0f), the program prints an error message followed by a thank-you message and quits the application.
The program in Code Listing 7.12 shows how to use try, catch, and finally. First of all, try, catch, and finally each have a code block. Inside the body of the try block, we place the code we are attempting to execute. Notice that there is a line in this body of the try block that contains the throw keyword. When the denominator is 0.0f, this line of code will create a new IllegalArgumentException object, and this Exception object will be thrown.
Inside the Scanner class’s nextFloat method, it checks that the value entered by the user is actually a float. If the user enters some string, e.g., ninety four, the nextFloat method will create and throw a new InputMismatchException object. Also note that the InputMismatchException requires an import—it is a class belonging to the java.util package.
Following a try block, we can include as many catch blocks as we like. Each catch block can be specifically designed to catch certain types of exceptions. The first catch blocks in a list of catch blocks should always catch the most specific exceptions because only one catch block will execute. In Code Listing 7.12, there are three catch blocks designed to catch InputMismatchException, then IllegalArgumentException, and then any other Exception object. The first catch block will catch the exception thrown by s.nextFloat() when the user does not input a float. The second catch block catches the IllegalArgumentException that we throw when the user attempts to divide by zero. The third catch block will catch any other exceptions thrown by the code that were not already caught by the previous catch blocks.
In the body of each catch block, we have the option of examining the exceptions that were thrown. In the final catch block, I have printed out the exceptions message by calling the e.getMessage() method. All exceptions have a getMessage method that can be used to show the user some extra information about what went wrong.
The finally block is optional. When used, it follows all the catch blocks. The finally block is always executed, regardless of whether or not an exception was thrown and caught—the code of the finally block will execute. I have used the finally block to close the scanner.
If our methods can potentially throw a particular exception and we do not offer any chance of catching and responding to the exception, we should mark the method with the throws keyword to indicate to any potential callers that this method may raise an exception. Code Listing 7.13 shows an alternative code that simply mentions that main throws exceptions while offering no try/catch to handle them.
Code Listing 7.13: Throws Keyword
import java.util.Scanner; import java.util.InputMismatchException; public class MainClass { public static void main(String[] args) throws InputMismatchException, IllegalArgumentException { float numerator = 0.0f; float denominator = 0.0f; Scanner s = new Scanner(System.in); System.out.print("Enter a numerator: "); numerator = s.nextFloat(); System.out.print("Enter a denomintor: "); denominator = s.nextFloat(); if(denominator == 0.0f) throw new IllegalArgumentException(); System.out.println(numerator + " divided by " + denominator + " is equal to " + (numerator / denominator)); System.out.println("Thank you for your time."); } } |
In Code Listing 7.13, the important line is highlighted in yellow. We state that our method potentially throws the two exceptions. This way, any method that calls this one might respond with their own try/catch blocks. As it happens, this is the main method, and the JVM itself called it to start our application. If this method throws an exception, the program will crash.
Tip: If you want to use a method provided by the Java libraries, such as Scanner.nextFloat(), you can hover over the nextFloat token in Eclipse and you will be shown a description of the method. Part of this description includes the exceptions that the methods could potentially throw and that you might want to include catch blocks for when you call the method.
Code Listing 7.14 shows an example of a simple guessing game. I have included this code so that folks new to programming can see how the control structures, variables, and other mechanisms of Java all go together to create a small game. This program introduces a few new concepts, such as the Random class (from math), but most of this program has been covered in detail.
Code Listing 7.14: Monty Hall Game
// Import all classes from java.util. import java.util.*; public class MainClass { public static void main(String[] args) { // Declare a pseudorandom number generator called r. Random r = new Random(); // Declare a new Scanner called scanner. Scanner scanner = new Scanner(System.in); // Select a random number from 1, 2, or 3. int doorWithCar = r.nextInt(3) + 1; System.out.println("There are three doors before you. " + "Behind two doors, you will find a goat, but " + "behind the third, there is a brand new car!\n"); // Declare a variable to store the door the user selects. int selectedDoor = 0; // Loop until they guess the right door: while (selectedDoor != doorWithCar) { System.out.println("Which door would you like to open?"); // Read a door from the user. selectedDoor = scanner.nextInt(); if (selectedDoor < 1 || selectedDoor > 3) { System.out.println("The doors are 1, 2 or 3..."); selectedDoor = 0; } else if (selectedDoor == doorWithCar) { System.out.println("Yes, you won a car!!!!"); } else { System.out.println("Nope, that's a goat..."); selectedDoor = 0; } }
if(scanner != null) scanner.close(); } } |
Line 1 shows how to import multiple classes with a single import statement. The star (or asterisk), “*”, is used as a wild card that means import all of the classes from java.util. This is handy because in the code we use both a Scanner and a Random object. We could have used two import statements if we had preferred. The Random object is used to generate random numbers, and I have used it in Code Listing 7.14 to hide the car behind one of the three doors. Random does not actually generate a random number—computers cannot generate random numbers—but they can generate a sequence of numbers that will seem random (sometimes called pseudorandom numbers).
The following is an example of interaction with the Monty Hall program above.
There are three doors before you. Behind two doors, you will find a goat, but behind the third, there is a brand new car!
Which door would you like to open?
19
The doors are 1, 2 or 3...
Which door would you like to open?
1
Nope, that's a goat...
Which door would you like to open?
2
Nope, that's a goat...
Which door would you like to open?
3
Yes, you won a car!!!!
This Monty Hall program is far more complicated than the previous programs we have studied, but it is a good example of how to create a coherent application from the basic building blocks of Java. Using only what we have studied so far, we can already make small games and other applications. The best possible way to learn a new computer language is to play around with the code, to read source code from other programmers, and to try figuring out why it does what it does. I have used some comments that will help you understand the objective of this source.
Fizz Buzz is a common programming job interview question. It is easy to know what the different parts of a language do, such as a for loop, and an if statement. But this challenge is designed to test if a programmer is able to put the mechanisms together into a coherent working program.
The objective of this challenge is to print the numbers from 1 to 100 using print, except:
Every number that is evenly divisible by three, we should print “Fizz!” instead of the number.
Every number which is evenly divisible by five, we should print “Buzz!” instead of the number.
Numbers which are divisible by three and five, we should print “Fizz!Buzz!”.
The output of your program should be as follows:
1 2 Fizz! 4 Buzz! Fizz! 7 8 Fizz! Buzz! 11 Fizz! 13 14 Fizz!Buzz! 16 17 Fizz! 19 Buzz! Fizz! 22 23 Fizz! Buzz! 26 Fizz! 28 29 Fizz!Buzz! 31 32 Fizz! 34 Buzz! Fizz! 37 38 Fizz! Buzz! 41 Fizz! 43 44 Fizz!Buzz! 46 47 Fizz! 49 Buzz! Fizz! 52 53 Fizz! Buzz! 56 Fizz! 58 59 Fizz!Buzz! 61 62 Fizz! 64 Buzz! Fizz! 67 68 Fizz! Buzz! 71 Fizz! 73 74 Fizz!Buzz! 76 77 Fizz! 79 Buzz! Fizz! 82 83 Fizz! Buzz! 86 Fizz! 88 89 Fizz!Buzz! 91 92 Fizz! 94 Buzz! Fizz! 97 98 Fizz! Buzz!
Tip: In order to discover if an integer j is divisible by another integer q, check if the remainder after division is 0 with the modulus operator. If the result of j%q is equal to 0, that means j is evenly divisible by q. For example, 20%4=0 because 20 is divisible by 4, but 81%6=3, and 3 is not 0, which means 81 is not divisible by 6. And, if an integer j is divisible by two integers, q and p, then j%(q*p)=0.
There are many solutions to the classic Fizz Buzz problem. Code Listing 7.15 shows one.
Code Listing 7.15: Fizz Buzz Solution
public class MainClass { public static void main(String[] args) { // Use a for loop to count from 1 to 100. for(int i = 1; i <= 100; i++) { // If the number is divisible by 3 and 5, print Fizz!Buzz! if(i % 15 == 0) System.out.print("Fizz!Buzz!"); // Otherwise, if the number is divisible by 3, print Fizz! else if(i % 3 == 0) System.out.print("Fizz! "); // Otherwise, if the number is divisible by 5, print Buzz! else if(i % 5 == 0) System.out.print("Buzz!" ); // Otherwise, just print the number itself. else System.out.print(i + " "); } } } |