- 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); } }
- 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
- Fix the errors by importing the Scanner class.
import java.util.Scanner;
- 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.
- Fix the error by initializing okay to false.
boolean okay = false;
- Ensure the code compiles.
- 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(); } }
- 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.
- Fix main’s signature.
public static void main(String[] args){
- 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.