Java Reference
In-Depth Information
String
array; that is, it contains
String
objects. (Strings are not a primitive type,
like integers and boolean values in Java: they are full-fledged objects.) Once you
extract the
i
th
String
from the array, you invoke the
charAt()
method of that
object, passing the argument
j
. (The
.
character in the expression refers to a
method or a field of an object.) As you can surmise from the name (and verify, if
you want, in a reference manual), this method extracts the specified character
from the
String
object. Thus, this expression extracts the
j
th character from the
i
th command-line argument. Armed with this understanding, you should be able
to make sense of the rest of Example 1-5.
Example 1−5: Reverse.java
package com.davidflanagan.examples.basics;
/**
* This program echos the command-line arguments backwards.
**/
public class Reverse {
public static void main(String[] args) {
// Loop backwards through the array of arguments
for(int i = args.length-1; i >= 0; i--) {
// Loop backwards through the characters in each argument
for(int j=args[i].length()-1; j>=0; j--) {
// Print out character j of argument i.
System.out.print(args[i].charAt(j));
}
System.out.print(" "); // Add a space at the end of each argument.
}
System.out.println();
// And terminate the line when we're done.
}
}
FizzBuzz Switched
Example 1-6 is another version of the
FizzBuzz
game. This version uses a
switch
statement instead of nested
if/else
statements to determine what its output
should be for each number. Take a look at the example first, then read the expla-
nation of
switch
.
Example 1−6: FizzBuzz2.java
package com.davidflanagan.examples.basics;
/**
* This class is much like the FizzBuzz class, but uses a switch statement
* instead of repeated if/else statements
**/
public class FizzBuzz2 {
public static void main(String[] args) {
for(int i = 1; i <= 100; i++) { // count from 1 to 100
switch(i % 35) { // What's the remainder when divided by 35?
case 0: // For multiples of 35...
System.out.print("fizzbuzz "); // print "fizzbuzz".
break; // Don't forget this statement!
case 5: case 10: case 15: // If the remainder is any of these
case 20: case 25: case 30: // then the number is a multiple of 5
System.out.print("fizz ");
// so print "fizz".