What is the general design pattern for declaring variables in a class?
I have a homework assignment to create a simple Java program which asks the user for a range of two variables. The program then creates a random variable from within this range and prompts the user to guess the number.
I'm having trouble understanding how to declare my variables. I'm not sure if I should declare variables as public
or private
, and static
or non-static
. When is it correct to use a public
/private
variable?
Also, how much code should I include in my main()
method? What is generally placed into the main()
method?
import java.util.Scanner;
import java.util.Random;
public class HiLo {
static int guess, guessCount, randomNumber, startRange, endRange;
static Scanner scan = new Scanner(System.in);
static Random random = new Random();
public static void main(String[] args) {
getRange();
playGame();
}
public static void getRange() {
System.out.println("Welcome! Enter integer for start of range (must be > 0)");
startRange = scan.nextInt();
System.out.println("Enter integer for end of range (must be >0)");
endRange = scan.nextInt();
randomNumber = random.nextInt(endRange - startRange + 1) + startRange;
System.out.println(randomNumber);
}
public static void playGame() {
guessCount = 0;
System.out.println("Enter guess or 0 to quit: ");
guess = scan.nextInt();
while (randomNumber != guess) {
if (guess == 0) {
break;
}
else if (randomNumber > guess) {
guessCount++;
System.out.println("Too Low");
System.out.println("Enter guess or 0 to quit: ");
guess = scan.nextInt();
}
else if (randomNumber < guess) {
guessCount++;
System.out.println("Too High");
System.out.println("Enter guess or 0 to quit: ");
guess = scan.nextInt();
}
}
if (randomNumber == guess) {
guessCount++;
System.out.println("Correct! That took you " + guessCount + " guesses.");
}
}
}