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 Do While Loops

Carl Sergile
Carl Sergile
16,570 Points

How to run console.printf in do while loop

How do you make it so that console.printf("Drumroll please.....%n"); run only when the loop is set to increment and gives you an integer greater than one. For example the code runs once and it says "Drumroll please....". But as soon as the number inside the loop gets bigger(lets say 2) the code runs:

"Drumroll please...." "Drumroll please...."

code:

`//Hit a strike int attempts = 0; boolean strike = false;

  do {
    console.printf("Drumroll please....%n");

    strike = luck.nextBoolean();
    attempts++;
  } while(!strike);


  console.printf("You got a strike in %d attempts! %n", attempts);
   System.exit(0);

`

1 Answer

andren
andren
28,558 Points

Your question is phrased in a slightly confusing way but if what you are asking if how to have the printf statement only execute, or execute differently based on some condition then the answer, as it often is when you only want to run code in certain conditions, is to use an if statement.

   //Hit a strike 
   int attempts = 0; 
   boolean strike = false;

 do {
    if (attempts == 0) {
    console.printf("Drumroll please....%n");
    } 
    else {
    console.printf("Drumroll please.... Drumroll please....");
    }

    strike = luck.nextBoolean();
    attempts++;
 } while(!strike);

 console.printf("You got a strike in %d attempts! %n", attempts);
 System.exit(0);

That code would achieve what you describe, "Drumroll please....%n" will only be printed the first time though the loop, and "Drumroll please.... Drumroll please...." will be printed all other times through the loop, the if else statement could of course be modified to change this behavior further if you wished.

Carl Sergile
Carl Sergile
16,570 Points

ahhhh I see. Didn't know I could combine the loops like this til literally 5mins ago. I put a while loop inside of a do while loop. Is this the case all the time? I can mix up the looping syntax as long as it makes sense and keep the scope of the loop I'm in if that makes sense. Oh and sorry if this/last question was confusing, super new to the world of Java.