Java Reference
In-Depth Information
The example also shows another style for comments. Anything, on any number of
lines, between the characters /* and the characters */ is a comment in Java and
ignored by the compiler. When one of these comments begins with /** ,asthe
one in this example does, then it is additionally a doc comment , which means its
contents are used by the javadoc program that automatically generates API docu-
mentation from Java source code.
Example 1−2: FizzBuzz.java
package com.davidflanagan.examples.basics;
/**
* This program plays the game "Fizzbuzz". It counts to 100, replacing each
* multiple of 5 with the word "fizz", each multiple of 7 with the word "buzz",
* and each multiple of both with the word "fizzbuzz". It uses the modulo
* operator (%) to determine if a number is divisible by another.
**/
public class FizzBuzz { // Everything in Java is a class
public static void main(String[] args) { // Every program must have main()
for(int i = 1; i <= 100; i++) { // count from 1 to 100
if (((i % 5) == 0) && ((i % 7) == 0)) // Is it a multiple of 5 & 7?
System.out.print("fizzbuzz");
else if ((i % 5) == 0)
// Is it a multiple of 5?
System.out.print("fizz");
else if ((i % 7) == 0)
// Is it a multiple of 7?
System.out.print("buzz");
else System.out.print(i);
// Not a multiple of 5 or 7
System.out.print(" ");
}
System.out.println();
}
}
The for and if/else statements may require a bit of explanation for programmers
who have not encountered them before. A for statement sets up a loop, so that
some code can be executed multiple times. The for keyword is followed by three
Java expressions that specify the parameters of the loop. The syntax is:
for( initialize ; test ; update )
body
The initialize expression does any necessary initialization. It is run once, before
the loop starts. Usually, it sets an initial value for a loop counter variable. Often, as
in this example, the loop counter is used only within the loop, so the initialize
expression also declares the variable.
The test expression checks whether the loop should continue. It is evaluated
before each execution of the loop body. If it evaluates to true , the loop is exe-
cuted. When it evaluates to false , however, the loop body is not executed, and
the loop terminates.
The update expression is evaluated at the end of each iteration of the loop; it does
anything necessary to set up the loop for the next iteration. Usually, it simply
increments or decrements the loop counter variable.
Finally, the body is the Java code that is run each time through the loop. It can be
a single Java statement or a whole block of Java code, enclosed by curly braces.
Search WWH ::




Custom Search