Program Logic

Unit 7 Index

Combining Structures Example

Example - Combining Repetition and Decision Structures for Validation

I have purposely omitted the 5-Step Solution Algorithm for this example.

Problem Statement

A program is to be written that will ask the end-user an even number. Each time the end-user fails to enter an even number, the program will ask for them for an even number. The only way to end the program is to enter an even number. Once an even number is entered, a thank you message is displayed.

Java Code

Below is a Java solution. I highly suggest you type it into our development environment. Develop a test plan that will make the program fail as well as succeed. Run the program according to your test plan. Your understanding will be enhanced if you step through this program using the NetBeans debugger.


import java.util.Scanner;

public class Example_3 {


	public Example_3() {
		getEvenNumber();
		//end the program
		System.exit(0);
	}//end constructor

	private void getEvenNumber() {

        int entry = 0;
        String userInput = "";

        Scanner input = new Scanner(System.in);
        System.out.println("This program only accepts even numbers");
        System.out.println("Please enter an even number");

        userInput = input.next();

        //the decision statement uses a regular expression
        //to check to see if the userInput variable is all numeric
        if(userInput.matches("[0-9]+")){

            entry = Integer.parseInt(userInput);
            while(entry % 2 != 0){
                System.out.println("Invalid entry");
                System.out.println("Please enter an even number");
                userInput = input.next();
                if(userInput.matches("[0-9]+")){
                    entry = Integer.parseInt(userInput);
                }
                else{
                   System.out.println("Really? I just wanted an even number.");
                   break;
                }
            }
        }
        else{
            System.out.println("Okay, Okay, I see you cannot play nice in the "
                    + "sandbox. Goodbye.");
        }



    }//end of method

}//end of class