Wednesday, February 5, 2014

Random Number Guess Program in Java

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

public class GuessNum {

public GuessNum() {        

        int numRandom = 0;  
        int numGuess;  
        int life = 5;  
        String want = "";  
        Random rand = new Random();  
        Scanner scan = new Scanner(System.in);

        do {
            int lifeLeft = 5;
            numRandom = rand.nextInt(9)+1;
           // System.out.print("the number:"+numRandom);
            System.out.print("\nGuess the Number [1..10]\n");
            System.out.print("===================\n");
            System.out.print("You have " + lifeLeft + " chances.\n");

            do {
                do {
                    System.out.print("What number do I have in mind: ");
                    numGuess = scan.nextInt();

                    if (numGuess < 1 || numGuess > 10)  
                        System.out.println("Invalid input. Range is 1-10.");  
                } while (numGuess < 1 || numGuess > 10);

                if (numGuess != numRandom && lifeLeft != 0)
                    System.out.println("Wrong! You only have " + --lifeLeft + " chances left.");

            } while (numGuess!=numRandom && lifeLeft > 0);

            if (numGuess == numRandom)
                System.out.println("Correct! -- in " + (life - lifeLeft) + " guess(es).");

            if (lifeLeft == 0) {
                System.out.println("You have no more lives..");
                System.out.println("This is the number: " + numRandom);
            }

            System.out.print("\nEnter 'y' if you want to play again or any other character to exit: ");
                want = scan.nextLine();
        } while (want.equals("y") || want.equals("Y"));
    }

    public static void main(String[] args) {          
        new GuessNum();
    }
}

No comments:

Post a Comment