第六章第三十八题(生成随机字符)(Generate random characters)

it2026-09-22  1

第六章第三十八题(生成随机字符)(Generate random characters)

*6.38(生成随机字符)使用程序清单6-10RandomCharacter中的方法,打印100个大写字母及100个一位数字,每行打印10个。 *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.参考代码: 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'); } } 结果显示: 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
最新回复(0)