Last Updated: February 25, 2016
·
314
· sprklo

GuessNum Lab

A simple program that demonstrates how to use java.util.Random
the computer calculates a 'random' number and the user tries to guess what it its based on the clues "too high" or "too low"

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

public class GuessNum
{
    private Random ranNum = new Random();
    private Scanner input = new Scanner(System.in);
    private int magicNum;
    private int guess;
    private int counter;

public void guessing()
{
    magicNum = 1 + ranNum.nextInt(1000);

    System.out.println("Take a guess: ");
    guess = input.nextInt();
    do
    {
        if(guess == 99999)
        { 
            System.out.printf("%d\n", magicNum);
            System.out.println("cheater, choose again: ");
            guess = input.nextInt();
        }
        else if (guess > magicNum)
        {
            System.out.println("your number was too high :( choose again: ");
            guess = input.nextInt();
        }
        else if (guess < magicNum)
        {
            System.out.println("your number was too low :( choose again: ");
            guess = input.nextInt();
        }
        counter++;
    }while (guess != magicNum);
    System.out.printf("YAY!! the magic num is %d you guessed right!! and it only took you %d times :P \n", magicNum, counter);
}

}