public class Main {

    public static void main(String[] args) {

        int number = 4;
        int finishNumber = 20;
        int evenNumbersFound = 0;

        while (number <= finishNumber){
            number++;             
            if (!isEvenNumber(number)) {                 
                continue;             
            }             
    
            System.out.println("Even number " + number);             
            evenNumbersFound++;             
            if(evenNumbersFound >=5){
                break;
            }
        }

        System.out.println("Total even numbers found is: " + evenNumbersFound);

    }

    public static boolean isEvenNumber(int number) {
        if ((number % 2) == 0) {
            return true;
        } else {
            return false;
        }
    }
}

I have completed a lecture on While statements. I didn’t very well understand it when I began the video a few days ago, so I decided to let it sink in and then come back to it. That helped somewhat although I found this lecture to be a bit terse. All the same I came up with a working program which uses a while statement (as well as other control flow statements) to list even numbers and give a count of the numbers listed.

It begins by declaring 3 integer-type variables. One is the number which is tested (and also by default the number which the count begins at). Another is the number at which to stop counting. The third is the number which is used to tally the even numbers counted.

Next there is a while loop. It continues to loop while the testing number is less than the number specified as maximum. One thing it always does so long as this while loop is looping, is add one to the testing number.

The while loop also contains an if statement. This if statement refers to the method at the bottom of the program. This method is a block of code which tests whether an inputted number is even or not. It returns true if it is even. The if statement referring to this method then continues through the while loop if true is returned because the number is even.

It then prints out the string “Even number ” and the testing number. And it adds one to the tally number.

There is a second if statement which tells it to break if the tally number is 5 or more.

Outside of the entire while statement, there is a line which is a statement to print out the string “Total even numbers found is: ” and the tally number. The end result is that it lists all the even numbers within given parameters and gives a total of those listed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s