第六章第三十八题(生成随机字符)(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.
下面是参考答案代码:
// https://cn.fankuiba.com
public class Ans6_38_page205 {
public static void main(String[] args) {
for (int count = 1; count <=100; count++) {
System.out.print(getRandomUpperCaseLetter()+""+getRandomDigitCharacter());
if (count * 2 % 10 == 0)
System.out.println();
}
}
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
/** Generate a random uppercase letter */
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
/** Generate a random digit character */
public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
}
适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)
发布在博客:(https://cn.fankuiba.com)