mercredi 7 août 2019

Error when trying to generate random number between a range

I am trying to prompts the user for two numbers where the first number is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. However, I get an instance error when attempting to generate a random number between the max and min range.

import java.util.Scanner; import java.util.Random;

public class MaxMin {

public static void main(String[] args) {

    Random rand;

    Scanner console = new Scanner(System.in);       

    System.out.print("Enter a min value: ");
    int max = console.nextInt();


    System.out.print("Enter a max value: ");
    int min = console.nextInt();

    System.out.print("Guess a number within the range inputted: ");
    int guess = console.nextInt();

    int randomNum = rand.nextInt((max - min) + 1) + min; // Error


    if (guess == randomNum) {
        System.out.print("Correct guess!");
    }

    else {
        System.out.print("Guess a number within the range inputted: ");
    }


}

}




Aucun commentaire:

Enregistrer un commentaire