Monday, December 12, 2016

Number Guessing Game in Java

/*Description: This program implements a famous number guessing game in programming.
* There is a serious error in this code. Spot it.
*@blankbug.
*/


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?");
//start the while loop 
while(gameOn){
   
    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");
    System.out.printf("Enter it again.\n");
    }else{
    System.out.printf("Your number is greater than mine.\n");
    System.out.printf("Try it again.");
    }
   
    }
    guess++;
if(guess>4){
System.out.printf("You missed all your chances.The no was %d", comNum);
break;
}
}
}


}

----------------------------------------------------------------------------------------------------------------------
REMEMBER: There is a serious error in this program.
HINT:  Check if.. else statement inside a while loop.

No comments: