In: Computer Science
I am trying to write a simple game in Java named GuessNumber.java to run on the command line. This program asks user to pick a number and the computer guesses the number repetitively until the guess is correct and will allow the user to set the lower and upper bound as command line parameters from where the picks the number. If no command line parameters are specified then the program uses a default of 1 to 99.
If you have any doubts, please give me comment...
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int upper, lower;
if (args.length == 2) {
lower = Integer.parseInt(args[0]);
upper = Integer.parseInt(args[1]);
} else {
lower = 1;
upper = 99;
}
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int random;
int guess;
random = rand.nextInt(upper - lower) + lower;
System.out.print("Please guess a number between " + lower + " to " + upper + " (inclusive): ");
guess = scan.nextInt();
while (guess != random) {
System.out.println("Your guess wrong! Try again!");
System.out.print("Please guess a number between " + lower + " to " + upper + " (inclusive): ");
guess = scan.nextInt();
}
System.out.println("Congratulations! You got it!");
}
}