You should never be afraid of or avoid making mistakes since that is the best way to learn. For this reason, try to break the program that you're working on from time to time to investigate error messages, and to see if those messages tell you something about the error(s) you've made.

Stack Trace

When an error occurs in a program, the program typically prints something called a stack trace, i.e., the list of method calls that resulted in the error.

Checklist for Troubleshooting

If your code doesn't work and you don't know where the error is, these steps will help you get started.

  1. Indent your code properly and find out if there are any missing parentheses.
  2. Verify that the variables used are correctly named.
  3. Test the program flow with different inputs and find out the sort of input that causes the program to not work as desired. If you received an error in the tests, the tests may also indicate the input used.
  4. Add print commands to the program in which you print out the values of the variables used at various stages of the program's execution.
  5. Verify that all variables you are using are initialized. If they aren't, a NullPointerException error will occur.
  6. If your program causes an exception, you should definitely pay attention to the stack trace associated with the exception, which is the list of method calls that resulted in the situation that caused the exception.
  7. Learn how to use the debugger. The earlier video will get you started.

Passing Test Input to Scanner

String input = "one\\n" + "two\\n"  +
                "three\\n" + "four\\n" +
                "five\\n" + "one\\n"  +
                "six\\n";
Scanner reader = new Scanner(input);

Passing a string to the constructor of the Scanner class replaces input read from the keyboard. As such, the content of the string variable input 'simulates' user input.

Unit Testing

Testing larger programs is challenging. One solution to this is unit testing, where small parts of the program are tested in isolation.

Unit testing refers to the testing of individual components in the source code, such as classes and their provided methods.

The writing of tests reveals whether each class and method observes or deviates from the guideline of each method and class having a single, clear responsibility.

The more responsibility the method has, the more complex the test. If a large application is written in a single method, writing tests for it becomes very challenging, if not impossible.