Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit Java loop? While-loop in a basic guessing game

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++;


        }
    }
}

}

like image 578
user2906011 Avatar asked Nov 20 '13 15:11

user2906011


1 Answers

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.

like image 153
Zach Latta Avatar answered Sep 28 '22 05:09

Zach Latta