Java · Beginner level

Beginner level · Module 5: Console Application Project in Java · Lesson 3 of 3

Validating Input and Testing the Program

Stop invalid input from crashing the program, test with a written plan, and present the finished application.

In this lesson you will

  • Use try/catch with NumberFormatException to validate typed numbers
  • Write and run a manual test plan, including edge cases

Key concepts

NumberFormatExceptiontry/catchedge casetest plan

The lesson

If a user types 'ten' where a number is expected, Integer.parseInt throws NumberFormatException and the program stops. Wrap the conversion in try/catch, print a helpful message and ask again in a loop until the input is valid.

A test plan lists inputs, the expected result and the actual result. Include normal cases, boundaries (zero, the largest allowed value) and invalid cases (letters, negative numbers, empty input). Testing what should fail is as important as testing what should work.

When presenting a program, show the main flow first, then one invalid input being handled, and explain one decision you made — for example why the totals live in SalesBook rather than in main.

Step by step

  1. Write a method readPositiveInt(prompt) that loops until valid input is given.
  2. Use it everywhere the program reads a number.
  3. Write a test plan with at least eight cases.
  4. Run every case and record the actual results.

Practice activity

Finish the Shop Sales Recorder with full input validation and run your eight-case test plan.

Expected result: No input crashes the program, and every test case's actual result matches the expected result or the bug is fixed.

Check your understanding

  1. Which exception does Integer.parseInt("ten") throw?

    Show answer

    NumberFormatException.

  2. Name three kinds of test case to include in a test plan.

    Show answer

    Normal values, boundary values and invalid input.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.