I'm making a simple guess a number game. In game, user should input minimum and maximum value and program should generate random number between this numbers, later user should try and guess the number.
This is one of my first programs, so I'd like to check my coding techniques, what should I do differently etc.
I have getInterval()
methode that I'm not sure I've done in best way, first I thought I should past two arguments (min and max) and change them in methode, but looks like I can do that like that in Java, so I've done it this way.
I'm going to make this game a bit more advanced later, but just want to check if this part is ok and if I should change some things before I move on.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int min=0;
int max=0;
min = getInterval("Min"); // Get minimum for guessing interval
max = getInterval("Max"); // Get Maximum for guessing interval
int randomNumber = getRandom(min, max); // generate random number between Min and Max
playRandom(min, max, randomNumber); // play the game
}
public static int getInterval(String text){
System.out.println("Please Input " + text + " number for guessing: ");
Scanner inputMin = new Scanner(System.in);
return Integer.parseInt(inputMin.nextLine());
}
public static int getRandom(int min, int max){
Random rand = new Random();
return rand.nextInt((max - min) + 1) + min;
}
public static void playRandom(int min, int max, int randomNumber){
boolean guess = false;
int numGuesses = 1;
while (!guess){
System.out.println("Enter your guess: ");
Scanner inputGuess = new Scanner(System.in);
int userGuess = Integer.parseInt(inputGuess.nextLine());
if (userGuess < randomNumber){
System.out.println("Too low!");
numGuesses++;
}
else if(userGuess > randomNumber){
System.out.println("Too high!");
numGuesses++;
}else{
System.out.println("You win! You tried " + numGuesses + " time(s) total");
guess = true;
}
}
}
}