I am trying to write a little game, but have stuck on how to prompt the user if they want to play again and how to exit the loop if they don't want to play again...
import java.util.Random;
import java.util.Scanner;
public class Guessinggame {
public static void main(String[] args) {
System.out.println("Welcome to guessing game! \n" + " You must guess a number between 1 and 100. ");
while (true) {
Random randomNumber = new Random();
Scanner g = new Scanner(System.in);
int number = randomNumber.nextInt(100) + 1;
int guess = 0;
int numberOfGuesses = 0;
while (guess != number){
System.out.print("Guess: ");
guess = g.nextInt();
if (guess > number ){
System.out.println( "You guessed too high!");
}else if (guess < number ){
System.out.println( "You guessed too low!");
}else{
System.out.println( "Correct! You have guessed "+ numberOfGuesses + " times. \nDo you want to play again? (y/n) ");
}
numberOfGuesses++;
}
}
}
}
You can use break
to get out of the current loop.
for (int i = 0; i < 10; i++) {
if (i > 5) {
break;
}
System.out.Println(i);
}
Prints:
0
1
2
3
4
5
However, a do-while
loop is probably better for your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With