0

my program won't do what I need it to do and I have been stuck on this issue for six hours. It prompts the user to enter how many times they would like to toss a coin, the program counts how many heads and tails were tossed and spits out the total heads and tails as well as the percentage that were rolled as heads. my issue is that the loop just ends once it goes through for the first time. it just stops and wont prompt the user to select another number or to press 0 to quit the program and return to the main menu, how can I fix this? Also how can I have the option to return to another loop. I've tried the break method and it doesn't work for me. I don't know I am really lost. How can I make it so this loop continues to toss the coin and still ask the users how many times they want to toss it? While at the same time allowing them to simply press 0 and exit this loop to return to the main menu? I didn't post that code here but it's a while loop with different sub options/games.

    if (anotherScanner.hasNext("t|T")){

    c = anotherScanner.next();
    usersSelection = true;
    System.out.println("");
    System.out.println("COIN TOSS SIMULATOR");
    System.out.println("");
    System.out.println("Enter 0 to quit. How many tosses?");


    Random rand = new Random();
    float headsCount = 0;
    float tailsCount = 0;
    Scanner scanMan = new Scanner(System.in);
    int numero = scanMan.nextInt();
    boolean headsOrTails;

    for (int j=0;j < numero;j++)
    {
    if (numero == 0) {break;}
    headsOrTails = rand.nextBoolean();

    if (headsOrTails == true)
    {
    headsCount++;
    }
    else 
    {
    tailsCount++;               

    System.out.println(headsCount + " heads and " + tailsCount + " tails means " + (headsCount/(headsCount+tailsCount)*100 + "% were heads"));
    }}}

1 Answers1

0

You can have a boolean flag variable before the outer loop, and use breaks/continues within the 2 nested loops to achieve your desired control flow.

Sample code:

boolean flag = false;
for (int i=0; i<N; i++)
{
   for (int j=0; j<N; j++)
   {
      if (j > i)
      {
         flag = true;
         break;
      }
   }
   if (flag)
   {
      break;
   }
}

...or use continues instead if you require. You might also like to change the inner loop termination condition as you need, ie. if (j > i)

Alternatively, if you are a fan of goto, you can also check out related SO answer post here, to immediately break out of the loop and jump to a particular label.

Sample code (from that SO page):

loops:
for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        break loops;
    }
}
Community
  • 1
  • 1
evandrix
  • 6,041
  • 4
  • 27
  • 38