CH7 – The do-while Loop

  1. Create a new class named DoWhile and add the following code to main.
public class DoWhile {
  public void main(String[] args){
    Scanner in = new Scanner(System.in);
    boolean okay;
    do {
    } while(!okay);
  }
}
  1. In this exercise we practice “baby steps” by compiling the code to ensure it compiles. Compile the code.

Note that when we do, two errors occur.

$ javac DoWhile.java
DoWhile.java:3: error: cannot find symbol
    Scanner in = new Scanner(System.in);
    ^
  symbol:   class Scanner
  location: class DoWhile
DoWhile.java:3: error: cannot find symbol
    Scanner in = new Scanner(System.in);
                     ^
  symbol:   class Scanner
  location: class DoWhile
2 errors
  1. Fix the errors by importing the Scanner class.
import java.util.Scanner;
  1. Compile and notice the new error.
$ javac DoWhile.java
DoWhile.java:7: error: variable okay might not have been initialized
    } while(!okay);
             ^
1 error

This is a common type of error when developing incrementally, fix the error by initializing okay. As an aside, note that when you declare a variable in a method, you must initialize it before using it. Class variables, which we discuss in later chapters, are different.

  1. Fix the error by initializing okay to false.
 boolean okay = false;
  1. Ensure the code compiles.
  2. Add the remaining code to the class.
// error in this class!
import java.util.Scanner;
public class DoWhile {
  public void main(String[] args){
    Scanner in = new Scanner(System.in);
    boolean okay = false;
    do {
      System.out.print("Enter a number: ");
      if(in.hasNextDouble()){
        okay = true;
      }
      else {
        okay = false;
        String word = in.next();
        System.err.println(word + " is not a number.");
      }
    } while(!okay);
    double x = in.nextDouble();
  }
}
  1. Compile and attempt to run the program. Although it compiles, it doesn’t run.
$ javac DoWhile.java
$ java DoWhile
Error: Could not find or load main class DoWhile.java

The reason it cannot run is that Java cannot find the main method, as the signature above is missing the static keyword.

  1. Fix main’s signature.
public static void main(String[] args){
  1. Compile and run the program.
$ java DoWhile
Enter a number: a
a is not a number.
Enter a number: b
b is not a number.
Enter a number: c
c is not a number.
Enter a number: 12

Of course, LearningLad has an excellent tutorial on this topic.