Flag This Hub

Loop Structures in Java

By


Loop Structures in Java

Previous hub = http://hubpages.com/hub/IfElse-Structures-in-Java

Loop structures in Java are like any other programming language loop structure, intended to repeat a block code a certain amount of times or until a condition has been met to stop the loop. This can be used in many ways in Java, loop through items in a vector/array, loop through letters in a string, loop for a certain number of times, all sorts of problems that can be solved with loops. There are a few types of loop structures in Java: while loop, do while loop, for loop, extended for loop.

While Loop

The while loop is generally used to repeat code while a condition isn't true, this can be very useful for validating input without you're program crasing, and there is a great method thats checks to see if the value in the next input stream is of a certain data type. The hasNextInt() will check the next input stream to see if it contains an integer value and by using this method as a condition of an if statement, we can catch if the user is inputting incorrect data and tell them they have done so.

For using the while loop we must use something called a priming read. A priming read is a incorrect value that you loop while the variable you wish to receive input is still equal to that incorrect value. For example, say we want the user to enter a grade that is within 0 and 100. We can initialize our while loop by first setting the number to the incorrect value(priming read), such as -1, and we can loop while the grade entered is above -1.

Example of a while loop:

Scanner input = new Scanner(System.in);

//Priming read

int grade = -1;

int amountOfGrades = 0;

double gradeAverage = 0;

int totalGradeScore = 0;

while (grade < 0)

{

System.out.println("Please enter the grades(-1 to quit)");

if (input.hasNextInt())

{

 

grade = input.nextInt();

if ( grade >= 0 && grade <= 100)

{

amountOfGrades++;

totalGradeScore += grade;

}

else

{

System.out.println("Incorrect grade value");

}

}

else

{

System.out.println("Incorrect grade value.");

}

}

gradeAverage = totalGradeScore / amountOfGrades;

System.out.println("The average of a class of " + amountOfGrades + " students was " + gradeAverage);

This code simply takes in the grades, if the value is incorrect( greater than 100 or not an integer value ), the program will display that is an incorrect grade value. If the grade is a correct value, it will add the grade to the totalGradeScore and increment the amountOfGrades. I have done this using shortcut assignment operators such as ++ or +=, which I will explain after. And this will loop through until the user enters a value that is less than 0, such as -1 which we used as our priming read in this case. The way the hasNextInt() method is working in the case above is that it will first try to collect the user input that is inside that if statement and actually checks right as the input is given and will abort the if statement if an incorrect value such as a String is being passed in, preventing our previous issue of our program crashing due to an exception!

Shortcut Assignment Operators

You can increment a value by 1 using the ++ operator. You can increment the value by any other value using the += assignment operator. You can also decrement the value using -- and -= operators.

Do while loop

A do while loop is very similar to a while loop except if will always go through the loop at least once, unlike the while loop where it is possible to loop 0 times through the code. The do while loop doesn't need a priming read, however you must initialize variables outside of the do while loop to be able to use them in your while statement for the loop, this is because instance variables are recognized within the boundaries of the curly braces it is contained within, therefore anytime you create a new if statement, switch structure, for loop, while loop, anything with new curly braces, you will not be able to use any created instance variables that were instantiated within those braces in other parts of your code, so keep that in mind when you get an error that says something like "variable name might not have been instantiated yet".

Example:

do

{

} while(expression);

This is the syntax of a do while loop, I don't really need to show you since you can easily do the same loop I had done earlier with a do while loop and that way you don't actually need a priming read, you simply just need to instantiate you're variables you are using in the loop before you actually begin the loop.

Example

variable declartions

while loop structure

{

      use the variables in here now that we have them instantiated.

}

Similar to what I just drew. Now on to For Loops.

For Loops

For loops are used to loop through a block of code a certain amount of times. There are useful methods such as .length() which will return the amount of characters in a String. I will demonstrate the syntax of a for loop to display a 10 second countdown.

for (int counter = 10; counter >= 0; counter--)

{

       if (counter >= 1)

       {

             System.out.println(counter + "...");

       }

       else

       {

               System.out.println("Blastoff!");

        }

}

So this simple for loop will start the counter variable at 10, display "10...", "9..", until it hits 0 then it displays "Blastoff!". The for loop syntax is similar to this:

for (counter initiator; expression to check for; code to do after the loop)

Counter iniator is like what I did by creating an int value inside my for loop called counter and initialized it to 10 for a countdown that runs down to zero. Seperated with a semi-colon, next is the expression which I am checking for the counter to see if it's greater than or equal to 0 before I stop the loop, it checks this expression everytime the loop starts again. The last is the code that is always done at the end of the loop, make sure to  change the value that is being used for the expression to prevent your code from becomming an infinite loop.

I hope you enjoyed this information I will be writing another tutorial shortly.

Comments

No comments yet.

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working