Java Reference
In-Depth Information
With the sh or bash shell, the command is:
$ CLASSPATH=.:/home/david/jenut2; export CLASSPATH
You may want to automate this process by setting CLASSPATH in a startup file, such
as autoexec.bat on Windows systems or .cshrc on Unix systems (under csh ).
With your CLASSPATH set, you can now go ahead and compile and run the Hello
program. To compile, change directories to the examples/basics directory that
holds Hello.java . Compile the program as before:
% javac Hello.java
This creates the Hello.class file.
To run the program, you invoke the Java interpreter as before, but now you must
specify the fully qualified name of the program, so that the interpreter knows
exactly which program you want to run:
% java com.davidflanagan.examples.basics.Hello
Because you've set the CLASSPATH , you can run the Java interpreter from any direc-
tory on your system, and it will always find the correct program. If you get tired of
typing such long class names, you may want to write yourself a batch file or shell
script that automates the process for you.
Note that all Java programs are compiled and run in this way, so we won't go
through these individual steps again. Of course, one step you don't have to repeat
is typing in all the examples. You can download the example source code from
http://www.davidflanagan.com/javaexamples2 .
FizzBuzz
FizzBuzz is a game I learned long ago in elementary-school French class, as a way
to practice counting in that language. The players take turns counting, starting
with one and going up. The rules are simple: when your turn arrives, you say the
next number. However, if that number is a multiple of five, you should say the
word “fizz” (preferably with a French accent) instead. If the number is a multiple
of seven, you should say “buzz.” And if it is a multiple of both, you should say
“fizzbuzz.” If you mess up, you're out, and the game continues without you.
Example 1-2 is a Java program named FizzBuzz that plays a version of the game.
Actually, it isn't a very interesting version of the game because the computer plays
by itself, and it doesn't count in French! What is interesting to us is the Java code
that goes into this example. It demonstrates the use of a for loop to count from 1
to 100 and the use of if/else statements to decide whether to output the number
or one of the words “fizz”, “buzz”, or “fizzbuzz”. (In this case, the if/else state-
ment is used as an if/elseif/elseif/else statement, as we'll discuss shortly.)
This program introduces System.out.print() . This method is just like Sys-
tem.out.println() , except that it doesn't terminate the line of output. Whatever is
output next appears on the same line.
Search WWH ::




Custom Search