简体   繁体   中英

Java: Generating “00” as a possible Math.random output

I'm creating a "roulette wheel" for a programming class assignment. This wheel generates random numbers from 0 to 36 using Math.random. One part of the assignment is to add "double zero" (00) as a possible output. Is it possible to do so through this equation?

     spin = (int) (Math.random()*(37 - 0)) + 0;

Assuming you want 00 and 0 to be a separate output, you will need to get a String instead, as integers treat the two as the same value. An option I thought of is to use a 39th possible output. You could add this in your code below:

String getSpin() {
    int spin = (int)(Math.random() * 38);
    if (spin == 38) return "00";
    else return Integer.toString(spin);
}

When you want to print 00 you should take 0 convert it to string and add "0" to it and print it as 00 and in the application logic use only one 0 and make the app give it double change of hitting it

"00" can be NOT integer in Java so we can use String type for "00". I thought we can prepare String array contains numbers as string from 00 to 36, then generate random number from 0 to 37 because length of string array is 38. And then get a value from array at position for the random number.

I coded and put it in this answer, hope it can help you. Cheers your assignment.

public static void main(String[] args) {
    // Generate numbers as String from 00 to 36
    String numbers[] = new String[38];
    numbers[0] = "00";
    for(int i=1; i<numbers.length; i++) {
        numbers[i] = Integer.toString(i-1);
    }

    // Generate random number
    int min = 0;
    int max = numbers.length - 1;
    int randomNum = min + (int)(Math.random() * ((max - min) + 1));

    // Return number at a position of randomNum
    System.out.println("Output: " + numbers[randomNum]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM