Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Difficulties With Loops

When I try it in Eclipse it starts at try 0 or wont do them one at a time or repeats same trys.

import java.util.Random;

public class DunkTankFor {

public static void main(String[] args) {
    Random skill = new Random();

        boolean isDunked = false;
        for (int ballsThrown = 0; !isDunked && ballsThrown <= 3; ballsThrown++) {
          System.out.printf("Try #%d ...%n", ballsThrown);
          isDunked = skill.nextBoolean();

        if (isDunked) {
          System.out.printf("Air punch!!!!%n");
        } else {


2 Answers

Bryanna Obrien
Bryanna Obrien
Courses Plus Student 4,700 Points

It's just from the way your loop is let up:

for (int ballsThrown = 0; !isDunked && ballsThrown <= 3; ballsThrown++)

With ballsThrown = 0, you're starting your count at 0 and ballsThrown++ increments up until you get to 3 balls thrown.(4 total ballsThrown 0, 1, 2, 3 )

If you want to count down, you could set your for loop:

for(int maxTries = 3; !isDunked && maxTries != 0; maxTries--) // I only changed ballsThrown to maxTries because when the loop begins, there are no balls thrown yet, but a maximum // possible number of times.

This also works to keep to to 3 tries:

for (int ballsThrown = 1; !isDunked && ballsThrown <= 3; ballsThrown++)