简体   繁体   中英

Generating random character and numbers in java

This is my first post. I am having a hard time writing this program... Write a program that generates a new license plate every time it is executed – one of the three styles described selected at random. Once the program decides on the pattern to be displayed, the letters and numbers must also be generated randomly. The program must run exactly 6 times (use a FOR loop).

One style of License plate is comprised of 3 letters + a space + 2 digits followed by a single letter. Yet another is one letter followed by 3 digits then a space and3 more letters. The final type has 2 letters followed by two digits then a space followed by three letters.

Here's my approach:

public static void main(String[] args) {
    for(int i = 0; i < 6; ++i) {
        double random = Math.random();
        if(random < 0.33) {
            System.out.println(style1());
        }
        else if(random < 0.66) {
            System.out.println(style2());
        }
        else {
            System.out.println(style3());
        }
    }
}

public static String style1() {
    return join(randomLetter(), randomLetter(), randomLetter(), ' ', randomDigit(), randomDigit(), randomLetter());
}

public static String style2() {
    return join(randomDigit(), randomDigit(), randomDigit(), ' ', randomLetter(), randomLetter(), randomLetter());
}

public static String style3() {
    return join(randomLetter(), randomLetter(), randomDigit(), randomDigit(), ' ', randomLetter(), randomLetter(), randomLetter());
}

public static char randomLetter() {
    return (char)(65 + (int)(Math.random()*26));
}

public static char randomDigit() {
    return (char)(48 + (int)(Math.random()*10));
}

public static String join(char ...args) {
    String result = "";
    for(int i = 0; i < args.length; ++i) {
        result += args[i];
    }
    return result;
}

Explanation

When in doubt, create a function for it.

The functions randomDigit and randomLetter return a random digit and letter respectively, in char format.

The style functions return the license plate in the format you mentioned (although IDK why style 3 has 7 chars and not 6). The join function is just something I wrote to easily combine the random letters and/or digits.

Sample Output

517 ONB
GLK 59R
NGD 73D
CP32 RPX
HH76 YPY
ZD88 AAV

and

ZI10 YNH
522 QZG
MZV 04A
QGK 70F
146 EBW
IFM 46A

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