I am a beginner to Java and have just written a number guessing game which involves guessing numbers from 1 to 10. I would like to improve my code by sticking strictly to conventions, improving code efficiency and forming good coding habits from the beginning.
Main class:
public class Main {
public static void main(String[] args) {
while (GuessingGame.play) {
GuessingGame.play();
}
}
}
GuessingGame class:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static boolean play = true;
private static int number = 0;
private static int guess = 0;
private static Random random = new Random();
private static Scanner scanner = new Scanner(System.in);
private static int nextInt(Random r, int lower, int higher) {
int ran = r.nextInt(higher - lower);
return (int) lower + ran;
}
public static void play() {
number = nextInt(random, 1, 10);
System.out.println("Insert your guess from 1-10!");
guess = scanner.nextInt();
if (guess == number) {
System.out.println("Correct!");
play = false;
} else {
System.out.println("Wrong! The number is: " + number);
System.out.print("Do you want to try again? Y/N");
String s = scanner.next();
play= s.equalsIgnoreCase("Y") ? true : false;
}
}
}