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);
}
}
Written by Katie Riley
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Java
Authors
Related Tags
#java
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#