samedi 24 avril 2021

How to let the user attempt many times?

import java.util.Scanner; import java.util.Random;

/*

    1. the user can attempt many times and you need to display the number of successful attempt
    1. the range of random number 1..49
    1. output >> You successfully guess the number in 16 attempts
    1. output >> Do you want to play again?
  • */

public class GuessingGame {

public static void main(String[] args) {
    Scanner uInput = new Scanner(System.in);
    Random randNum = new Random();
    int guessNumber, number, count=0;
    String in;
    char again; 
    
    System.out.println("Welcome to Guessing Game");
    do {
            number = randNum.nextInt(50); // random number in the range of 1..50
    
            for(int i=0; i<5; i++)
            {
                System.out.println("Enter a number to guess: ");
                guessNumber = uInput.nextInt(); // get guess number from user
                
                if(guessNumber > number)
                {
                    System.out.println("Too big");
                }else if(guessNumber < number)
                {
                    System.out.println("Too small");
                }else
                {
                    System.out.println("Success");
                    count+=1;
                    return;
                }
            }
            System.out.println("You successfully guess the number in "+count);
            System.out.println("Do you want to play again? ");
            in = uInput.nextLine();
            
            again = in.charAt(0); //again will hold the first character from in var
            
    }while(again =='Y'|| again =='y');
    System.out.println("Guessing game terminate, thank you");
}

}




Aucun commentaire:

Enregistrer un commentaire