Skip to main content

How to use for loops in Java

For loops in Java

Credit: Adam Sinicki / Android Authority

For loops in Java are just one type of loop that can be used to repeat a code block for iterative operations. If you need to open a text file for example, then you might use a loop to go through each line of the document and print it to the screen.

Likewise, games often use a “game loop” which loops around every time the frame is refreshed to check for inputs and update the positions of enemies, physics items, etc.

See also: How to use loops in Java

For loops in Java are extremely powerful and lend themselves to many different coding applications. In this post, we will explain how to use them, and look at more advanced concepts such as labelling.

How to use for loops in Java

What sets a for loop apart from other types of loop in Java, is that it has a fixed number of iterations. The syntax for a for loop in Java is:

for (declare variable; condition; increment) {

Everything inside the curly brackets (code block) will then be executed repeatedly until the condition is met. For example:

    for (int n=1; n<=100; n++) {
      System.out.println(n);
    }

This will count to 100 and print the numbers to the screen.

Break and continue

Now you understand the basics of for loops in Java. However, there are a number of more advanced concepts that can help you to write smarter code and better loops.

For example: break and continue.

Break is a keyword that will end the loop at any point. This could be useful if you want to let the user hit “esc” to stop the game for instance.

    for (int n=1; n<=100; n++) {
      System.out.println(n);
      if (n == 30) {
        break;
      }
    }

Continue, meanwhile, will restart the loop at the beginning. This means you can choose to skip a portion of the code block for a particular iteration.

See also: How to write your first Android game in Java

In a game scenario, this might be useful if the player presses “pause.”

Nested for loops

There is nothing to stop you from playing a for loop inside a for loop. This is referred to as a “nested loop” and you can repeat this process as many times as you deem necessary.

    for (int n=1; n<=10; n+=10) {
      System.out.println(n);
      for (int i=1; i<=100; i++) {
        System.out.println(i * n);
      }
    }

The following will count to 100 but show the number “1” twice.

The only problem when doing this, is that if you use break or continue at any point, you will break out of every level.

Labels are a useful tool that can be used with for loops in Java. Labels allow you to choose precisely which loop you want to break and where you wish to go in your code. You use them simply by choosing a name for your loop and then adding them just before your loop code using a colon.

public static void main(String []args){

    outerloop:
        for (int n=1; n<=10; n+=10) {
            System.out.println(n);

            innerloop:
                for (int i=1; i<=100; i++) {
                System.out.println(i * n);
                if (i == 50) {
                    break innerloop;
                }
            }
        }
     }

Now you’re in the loop!

Now you should have a handle on how to use for loops in Java.

Don’t forget to check out our list of the best resources to learn Java if you want to really develop your coding skills. There, you’ll find courses like the Complete Java Bundle, which Android Authority readers can sign up to for just $39. That’s a huge 96% discount on the $



source https://www.androidauthority.com/for-loops-in-java-1154602/

Comments

Popular posts from this blog

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

LIVE Day Trading Morning Show for Tuesday!

LIVE Day Trading Morning Show for Tuesday! via YouTube https://www.youtube.com/watch?v=vgagRBXRJM0 Android Tips and Tricks working hard to get the latest and useful tips and techniques that help you to solve a problem or improve your productivity.

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...