Java 101: Foundations

Java 101: Deciding and iterating with Java statements

Use statements to make decisions, iterate, and perform other tasks in your Java programs

1 2 3 Page 3
Page 3 of 3

Listing 1. Guess.java

class Guess
{
   public static void main(String[] args) throws Exception
   {
      outer:
      while (true)
      {
         System.out.println("I'm thinking of a number between 0 and 9.");
         int number = (int) (Math.random() * 10);
         while (true)
         {
            int guessNumber;
            while (true)
            {
               System.out.println("Enter your guess number between 0 and 9.");
               guessNumber = System.in.read();
               while (System.in.read() != '\n');
               if (guessNumber >= '0' && guessNumber <= '9')
               {
                  guessNumber -= '0';
                  break;
               }
            }
            if (guessNumber < number)
               System.out.println("Your guess is too low.");
            else
            if (guessNumber > number)
               System.out.println("Your guess is too high.");
            else
            {
               System.out.println("Congratulations! You guessed correctly.");
               while (true)
               {
                  System.out.println("Press n for new game or q to quit.");
                  int ch = System.in.read();
                  while (System.in.read() != '\n');
                  if (ch == 'n')
                     continue outer;
                  if (ch == 'q')
                     break outer;
               }
            }
         }
      }
   }
}

Guess demonstrates several statements and other fundamental features presented in previous articles. The main() method presents a while statement that generates a new number and gives you a chance to guess it. Expression (int) (Math.random() * 10) multiplies random()'s return value by 10 to change the range to 0.0 to almost 10.0, and converts the result to an integer ranging from 0 through 9.

After generating the number, main() executes an inner while statement to handle all of the guesswork. It repeatedly prompts for a guess, converts the pressed key's Unicode character value to a binary integer value from 0 through 9, and determines whether the user has guessed correctly or not. A suitable message is output. Users who guess correctly are given the chance to play a new game by pressing n, or to quit the application by pressing q.

An interesting part of the source code is while (System.in.read() != '\n');. I use this statement to flush the line separator character(s) (e.g., \r\n on Windows) from the operating system's keyboard buffer. If I don't do this, you'll see multiple prompts because each separator character will be interpreted as an attempt to enter a value from 0 through 9 (or n or q). If you are running Java on an older version of Mac OS, you'll probably have to replace \n with \r, which is the Mac's line separator. No changes are necessary when running on Linux or Unix, whose line separator is \n. (You can make the code portable by working with the standard class library's System class, which offers access to the line.separator property. I'll leave this task as a future exercise for when you're more comfortable with Java's classes and methods.)

Compile Listing 1 as follows:

javac Guess.java

Then run the application:

java Guess

Below is the output from a sample run:

I'm thinking of a number between 0 and 9.
Enter your guess number between 0 and 9.
5
Your guess is too high.
Enter your guess number between 0 and 9.
2
Your guess is too low.
Enter your guess number between 0 and 9.
3
Your guess is too low.
Enter your guess number between 0 and 9.
4
Congratulations! You guessed correctly.
Press n for new game or q to quit.
q

In conclusion

Statements are the workhorses of a Java application. Mastering them along with the other fundamental language features will help you develop a solid foundation on which to build your knowledge of more advanced language features. We'll begin this expansion in the next article, where I will introduce you to Java classes and objects.

1 2 3 Page 3
Page 3 of 3