In this quick mini-project we will put in to practice different types of loop like for loops and while loops. Prepare to go loopy. Actually it’s really simple.

  • The courses above are up to 95% off - by clicking on ad above.

To get started Create a new Android project and enter Loops in the Aplication Name field and enter LoopsActivity in the Activity Name field. When Android Studio has finished generating the project read on.

Delete the generated code in LoopsActivity.java then enter the required code that we need to work within as shown below and as explained in the mini-project Game variables demo.

import android.app.Activity;
import android.os.Bundle;

public class LoopsActivity extends Activity {

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Our Java code will start here

        // !!Our code must end here - for now.
    }
}

Now we can get on with doing a bit of looping. Enter the following code in the usual place as indicated by the starting and ending comments.

        // Our Java code will start here

        // First let's do a countdown with a while loop
        int x = 10;

        while(x > 0){

            x--;
            // x decreases by one each pass through the loop

            Log.d("Inside the loop:"," x = " + x);

        }

        Log.d("Outside the loop:","I'm free.");

        // Now let's use the break keyword
        x = 0;
        int tooBig = 10;

        while(true){

            x++; //I am going to get mighty big!
            Log.d("Inside the loop:"," x = " + x);

            if(x == tooBig){
                Log.d("Too big-"," Going to break out");
                break;
            } // No you're not haha.

            //code reaches here only until x = 10

        }

        Log.d("Outside the loop:"," x = " + x);

        // Now let's try a for loop
        for(int i = 10; i > 0; i--){

            // countdown
            Log.d("Inside the loop:"," i = " + i);

        }

        Log.d("Outside the loop:","Blast off!");

        // !!Our code must end here - for now.

Run the program and then we can take a look at the output in the Logcat window.

In the code above, first we count from 10 to 0 with a while loop:
while_loop_output

After this we attempt to keep counting forever with an infinite loop but break out when x = tooBig.
while_loop_with_break_output

Finally, in the for loop, we do another countdown but we also initialize i and set the condition of the loop all within the loop initialization line.
for_loop_output

  • The courses above are up to 95% off - by clicking on ad above.


Before we get dizzy from all this looping let’s look at a tutorial on Java methods.

Please visit the Android category of our game coding bookstore for beginners