0

How do I give my math.random a parameter in such a way that I will always receive at least, but not more than 3 digits? I'm currently in my first programming class at a community college, and this is an assignment for a small lottery program in Java. Any help or more of an in-depth explanation would be highly appreciated. Thank you!

//randomly generate 3 digit lottery number
    int lottery = (int)(Math.random() * 1000);

    System.out.println(lottery);

    int lotteryDigit1 = lottery / 100;
    int lotteryDigit2 = lottery / 10 % 10;
    int lotteryDigit3 = lottery % 10;

    System.out.println(lotteryDigit1 + " digit 1 ");
    System.out.println(lotteryDigit2 + " digit 2 ");
    System.out.println(lotteryDigit3 + " digit 3 ");

To help clarify the basis on which I am writing this program, here is a similar program that generates "2" random numbers for lottery. My job is to modify it to create 3 random numbers.

public static void main(String[] args) 
{

    //generate lottery number
    int lottery = (int)(Math.random() * 100);

    //prompt the user to enter a guess
    Scanner input = new Scanner (System.in);
    System.out.println("Enter your lottery pick (two digits): ");
    int guess = input.nextInt();

    //get digits from lottery
    int lotteryDigit1 = lottery / 10;
    int lotteryDigit2 = lottery % 10;

    //get digits from guess
    int guessDigit1 = guess / 10;
    int guessDigit2 = guess % 10;

    System.out.println("The lottery number is " + lottery);

    //check the guess
    if (guess == lottery)
        System.out.println("Exact match: you win $10,000");
    else if (guessDigit2 == lotteryDigit1 && guessDigit2 == lotteryDigit2)
            System.out.println("Match all digits: you win $3,000");
    else if (guessDigit1 == lotteryDigit1
            || guessDigit1 == lotteryDigit2
            || guessDigit2 == lotteryDigit1
            ||guessDigit2 == lotteryDigit2)
        System.out.println("Match one digit: you win $1,000");
    else
        System.out.println("Sorry, no match");






}

}

DevEarl
  • 18
  • 1
  • 3

2 Answers2

0

Use:

int lottery = 100 + (int) (Math.random()*899);

Use this line to generate a digit with at least 3 digits, and I don't know why you use lottery to base all the other random numbers? if you divide by 100 then for sure the resulting number will be less than 3 digits, and modulo 10 will give me 0-9 not 3 digits!!

Moshe Rabaev
  • 1,892
  • 16
  • 31
0

You can write a method with a minimum and a maximum bound for the random number. Both bounds are inclusive:

private void run() {
    int min = 100;
    int max = 999;
    int result = random(min, max);
    System.out.println(result);
}

private int random(int min, int max) {
    Random random = new Random();
    return min + random.nextInt(max - min + 1);
}
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51