Skip to content
Sign upLog in
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
9

How to loop a program?

ThomasWeaver
ThomasWeaver

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?

4 years ago

Voters

Comments

TopNew
2
Geocube101
Geocube101

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(); } }
4 years ago
Load more