Tuesday, December 13, 2016

Improved version of Guessing Game

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

public class GuessingNumber {
public static void main(String[]args){
//Generate a random number between 1 to 20
Random generator = new Random();
//store randomly generated number into variable comNum of type int
int comNum = generator.nextInt(20)+1;
//Create an object for Scanner class. 
Scanner scan = new Scanner(System.in);
boolean gameOn = true;
//create a variable to count the number of guesses. 
int guess =1;
//store user input into the variable num
int num;
System.out.printf("I am thinking of a number between 1 and 20.\n");
System.out.printf("Can you guess it?\n");
//start the while loop 
while(gameOn){
    if(guess<=4){
    System.out.printf("Enter a number to try.\n");
    num = scan.nextInt();
    if(num==comNum){
    System.out.printf("You guessed it right on %d tries\n",guess );
    break;
    }else{
    if(num<comNum){
    System.out.printf("Your guess # is lower than the one I am thinking off.\n");
   
    }else{
    System.out.printf("Your number is greater than mine.\n");
   
    }
   
    }
    }else{
    System.out.printf("You missed all your chances.The no was %d", comNum);
    break;
    }
    guess = guess+1;
}
scan.close();
}


}



Q. How to implement a loop to keep playing the game instead of restarting the program every time?

No comments: