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- Android Authority https://ift.tt/2R55yu0

Comments

Popular posts from this blog

5 best dialer apps and contacts apps for Android

Update: This list currently has Drupe as an entrant. It is a really good contacts and dialer app. However, recent security vulnerabilities are causing a big fuss about the app . The security vulnerabilities are gone now. Thus, we’re reinstating the app to our list with a word of caution to our readers. Hit the link to learn more. Dialer apps and contacts apps are a bit of a niche market. In most cases, the stock dialer and contacts app is more than good enough most of the time. However, there are some cases where it may be necessary. The Note 8 occasionally freezing while using the contacts app is a good example. In any case, there are a bunch of decent options, but only a few really good ones. Also, we considered doing separate lists for contacts apps and dialer apps. However, generally speaking, if you get one, you get the other too. Both lists would pretty much have the same apps. Thus, we’ve consolidated it into a single list here. Here are the best dialer apps and contacts a

Huawei Watch Fit hands on: The skinny Apple Watch

The Huawei Watch Fit looks like what you’d get if you threw a Huawei Band 4 Pro and a Huawei Watch GT 2 into an Apple Watch blender. It’s arguably a more fashion-forward wearable than a traditional fitness tracker or standard smartwatch, but it still packs enough smarts to fit in the “Huawei Watch” line rather than the “Huawei Band” family. Let’s take a closer look. Read more: The best fitness trackers Huawei Watch Fit design Credit: Kris Carlon / Android Authority The Huawei Watch Fit will instantly appeal to those who like Huawei’s smartwatch offerings but aren’t into the bulkiness of them. I’m a fan of a chunky watch personally, but the diminutive appeal of the Huawei Watch Fit is not lost on me. Beyond the eye-catching Cantaloupe Orange you see here, the Watch Fit also comes in Sakura Pink, Graphite Black, and Mint Green. The diminutive appeal of the Huawei Watch Fit is not lost on me. I’m less enamored by the unoriginal styling. It may lack creativity but will

Here’s a sneak peek at the design of the OnePlus 8T Cyberpunk 2077 Edition

Credit: OnePlus New teasers of the OnePlus 8T Cyberpunk 2077 Edition hint at the phone’s design. They show a large, horizontally placed rectangular camera housing. There’s also plenty of Cyberpunk branding on the back panel of the phone. OnePlus has announced the launch date and time for the Cyberpunk 2077 themed OnePlus 8T . The phone will be revealed in full on November 2 at 2 PM local time in China (2 AM ET). But that’s not all OnePlus has given us. The company has also posted a teaser image of the OnePlus 8T Cyberpunk 2077 Edition on Weibo , giving us a hint of what to expect from its design. The image shows the back of the phone, but it’s too dark to really tell anything. We popped the photo in an image editor, and after tweaking its brightness and contrast a bit, saw what the back panel design could look like. OnePlus 8T Cyberpunk 2077 edition official teaser OnePlus 8T Cyberpunk 2077 edition edited teaser As you can see in the image comparison above, the