一、习题介绍
第五章
Programming Exercise:5.15,5.24,5.40,5.50
二、习题及答案
*5.15 (Display the ASCII character table) Write a program that prints the characters in the ASCII character table from ! to ~. Display ten characters per line. The ASCII table is shown in Appendix B. Characters are separated by exactly one space.
*5.15(显示ASCII字符表)
写一个程序打印ASCII字符表中的字符!~.每行显示十个字符.
ASCII表如附录b所示.字符之间仅用一个空格分隔.
public class AsciiTable {
public static void main(String[] args) {
for (int i = 33; i <= 126; i++) {
System.out.print((char) i + " ");
if ((i - 32) % 10 == 0) {
System.out.println();
}
}
}
}
运行结果
*5.24 (Sum a series)编写程序对下列数列求和:
public class SumSeries {
public static void main(String[] args) {
double sum = 0.0;
for (int i = 1, j = 3; i <= 97 && j <= 99; i += 2, j += 2) {
sum += (double) i / j;
}
System.out.println("The sum of the series is: " + sum);
}
}
运行结果
5.40 (Simulation: heads or tails) Write a program that simulates flipping a coin one
million times and displays the number of heads and tails.
5.40(模拟:正面或反面)编写一个模拟掷硬币的程序百万次,显示正面和反面的次数。
public class CoinFlipSimulator {
public static void main(String[] args) {
final int FLIPS = 1000000;
int headsCount = 0;
int tailsCount = 0;
for (int i = 0; i < FLIPS; i++) {
if (Math.random() > 0.5) {
headsCount++;
} else {
tailsCount++;
}
}
System.out.println("Heads: " + headsCount);
System.out.println("Tails: " + tailsCount);
}
}
运行结果
*5.50 (Count uppercase letters) Write a program that prompts the user to enter a string and displays the number of the uppercase letters in the string
*5.50 (Count uppercase letters)编写一个程序,提示用户输入一个字符串,并显示该字符串中大写字母的个数
import java.util.Scanner;
public class UppercaseCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String input = scanner.nextLine();
scanner.close();
int uppercaseCount = 0;
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) {
uppercaseCount++;
}
}
System.out.println("大写字母的个数是:" + uppercaseCount);
}
}
运行结果
结语
有风有雨是人生的常态
迎难而上才能逆风翻盘
!!!