Chapter 6 Question 38 (Generate random characters)

Chapter 6 Question 38 (Generate random characters)

  • *6.38 (Generate Random Characters) Use the method in Listing 6-10 RandomCharacter to print 100 uppercase letters and 100 one-digit numbers, 10 per line.
    *6.38(Generate random characters) Use the methods in RandomCharacter in Listing 6.10 to print 100 uppercase letters and then 100 single digits, printing ten per line.
  • Reference Code:
package chapter06;

public class Code_38 {
    
    
    public static void main(String[] args) {
    
    
        for (int i = 1; i <= 200; i++) {
    
    
            if (i <= 100)
                System.out.print(RandomCharacter.getRandomUpperCaseLetter());
            else
                System.out.print(RandomCharacter.getRandomDigitCharacter());
            if (i % 10 == 0)
                System.out.print("\n");
        }
    }
}
class RandomCharacter {
    
    
    public static char getRandomCharacter(char ch1, char ch2) {
    
    
        return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
    }
    public static char getRandomLowerCaseLetter() {
    
    
        return getRandomCharacter('a', 'z');
    }
    public static char getRandomUpperCaseLetter() {
    
    
        return getRandomCharacter('A', 'Z');
    }
    public static char getRandomDigitCharacter() {
    
    
        return getRandomCharacter('0', '9');
    }
    public static char getRandomCharacter() {
    
    
        return getRandomCharacter('\u0000', '\uFFFF');
    }
}

  • The results show that:
FJOYKOMEHM
HKYEGHIUML
MKFQTUOHRP
RWVODHQXUI
EMPVKMBSIH
UQSKXLXQHF
RIZGMWIRYO
NKQIMITGMP
CSFEPWRRZZ
EZDFGHEQUX
7805935339
0190371742
0583184795
6189380079
0458389391
8499297748
5786171408
5156655037
3500072102
7427853825

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109230350