Ask coding questions

← Back to all posts
How to loop a program?
ThomasWeaver (15)

I made a game in java that generates a number and you have to guess the number that the computer generates. Once they get it right I'm supposed to ask if they want to play again, but I don't understand how I'm supposed to re-run the game. Anybody know?

Comments
hotnewtop
Geocube101 (627)

My first guess is a while loop.

import java.util.Scanner;

class Main
{
  public static void main(String[] args)
  {
    while (true != false)
    {
      //Game Code
      System.out.print("Play Again? ");
      Scanner sc = new Scanner(System.in);
      String again = sc.nextLine();
      if (again.equals("yes") == false)
      {
        sc.close();
        break;
      }
    }
  }
}

My second guess is to use functions:

import java.util.Scanner;

class Main
{
  public static void game()
  {
    //Game Code
    loopGame();
  }
  public static void loopGame()
  {
    System.out.print("Play Again? ");
    Scanner sc = new Scanner(System.in);
    String again = sc.nextLine();
    if (again.equals("yes") == true)
    {
      game();
    }
  }
  public static void main(String[] args)
  {
    game();
  }
}