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.

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(;
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 
    num = scan.nextInt();
    System.out.printf("You guessed it right on %d tries\n",guess );
    System.out.printf("Your guess # is lower than the one I am thinking off.\n");
    System.out.printf("Enter it again.\n");
    System.out.printf("Your number is greater than mine.\n");
    System.out.printf("Try it again.");
System.out.printf("You missed all your chances.The no was %d", comNum);


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

No comments: