基础篇课后习题答案,做了大部分,虽然不一定是最佳代码,但是保证每个都能运行,如有更好的答案,欢迎讨论
6.1 计算五角数
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 10 == 0) {
System.out.printf("%-6d\n", getPentagonalNumber(i));
} else {
System.out.printf("%-6d", getPentagonalNumber(i));
}
}
}
public static int getPentagonalNumber(int n) {
return n * (3 * n - 1) / 2;
}
6.2 求整数各位数字之和
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
Long num = scanner.nextLong();
System.out.print(num + "的各位数字之和为:" + sumDigits(num));
}
public static int sumDigits(long n) {
int sumTotal = 0;
char ch;
String str = String.valueOf(n).toString();
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
sumTotal = sumTotal + Integer.parseInt(String.valueOf(ch));
}
return sumTotal;
}
6.3 回文整数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数值:");
int num = scanner.nextInt();
if (isPalindrome(num) == true) {
System.out.println("这个数是回数");
} else {
System.out.println("这个数不是回数");
}
}
public static boolean isPalindrome(int number) {
return (number == reverse(number));
}
public static int reverse(int number) {
int revNum = 0;
while (number != 0) {
revNum = number % 10 + (revNum * 10);
number /= 10;
}
return revNum;
}
6.4 反方向显示一个整数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int num = scanner.nextInt();
System.out.print("该数字的倒序输出为:" + reverse(num));
}
public static int reverse(int number) {
int result = 0;
while (number != 0) {
result = (result * 10) + number % 10;
number /= 10;
}
return result;
}
6.5 对三个数排序
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入三个数字:");
double num1, num2, num3;
num1 = scanner.nextDouble();
num2 = scanner.nextDouble();
num3 = scanner.nextDouble();
displaySortedNumbers(num1, num2, num3);
}
public static void displaySortedNumbers(double num1, double num2, double num3) {
double changeNum;
if (num1 < num2) {
changeNum = num1;
num1 = num2;
num2 = changeNum;
}
if (num2 < num3) {
changeNum = num2;
num2 = num3;
num3 = changeNum;
}
if (num1 < num2) {
changeNum = num1;
num1 = num2;
num2 = changeNum;
}
System.out.print("升序排列后的结果为:" + num3 + "," + num2 + "," + num1);
}
6.6 显示图案
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个值:");
int n = scanner.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
for (int i = 1; i <= n; i++) {
for (int j = n - i; j >= 1; j--) {
System.out.printf("%3s", "");
}
for (int j = i; j >= 1; j--) {
System.out.printf("%3d", j);
}
System.out.println();
}
}
6.7 计算未来投资价值
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入投资额:");
double investmentAmount = scanner.nextDouble();
System.out.print("请输入年利率:");
double monthlyInterestRate = scanner.nextDouble();
monthlyInterestRate = monthlyInterestRate / 1200;
System.out.printf("%-8s%15s\n", "Years", "Future Value");
for (int i = 1; i <= 30; i++) {
System.out.printf("%-8d%15.2f\n", i, futureInvestmentValue(investmentAmount, monthlyInterestRate, i));
}
}
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years) {
double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), (years * 12));
return futureInvestmentValue;
}
6.8 摄氏度转换
public static void main(String[] args) {
System.out.printf("%-8s%-8s%8s%8s\n", "摄氏度", "华氏度", "华氏度", "摄氏度");
System.out.println("----------------------------------------");
for (int tpr1 = 40, tpr2 = 120; tpr1 >= 31 && tpr2 >= 30; tpr1--, tpr2 -= 10) {
System.out.printf("%-10.1f%-8.1f", (double) tpr1, celsiusToFahrenheit((double) tpr1));
System.out.printf("%11.1f%11.2f\n", (double) tpr2, fahrenheitToCelsius((double) tpr2));
}
}
public static double celsiusToFahrenheit(double celsius) {
return (9.0 / 5) * celsius + 32;
}
public static double fahrenheitToCelsius(double fahrenheit) {
return (5.0 / 9) * (fahrenheit - 32);
}
6.9 英尺转换
public static void main(String[] args) {
System.out.printf("%-9s%-8s%10s%9s\n", "英尺", "米", "米", "英尺");
System.out.println("----------------------------------------");
for (int i = 1, j = 20; i <= 10 && j <= 65; i++, j += 5) {
System.out.printf("%-10.1f%-8.3f", (double) i, footToMeter((double) i));
System.out.printf("%11.1f%11.3f\n", (double) j, meterToFoot((double) j));
}
}
public static double footToMeter(double foot) {
return foot * 0.305;
}
public static double meterToFoot(double meter) {
return meter * 3.279;
}
6.12 显示字符
public static void main(String[] args) {
printChars('1', 'Z', 10);
}
public static void printChars(char ch1, char ch2, int numLine) {
int num = 1;
for (int i = (int) ch1; i <= (int) ch2; i++) {
System.out.printf("%2c", (char) i);
if (num % numLine == 0) {
System.out.println();
}
num++;
}
}
6.13 数列求和
public static void main(String[] args) {
System.out.println("i" + " " + "m(i)");
System.out.println("--------------------");
for (int i = 1; i <= 20; i++) {
System.out.printf("%-2d%17.4f\n", i, subTotal(i));
}
}
public static double subTotal(int i) {
double result = 0;
for (int j = 1; j <= i; j++) {
result = result + ((double) j / ((double) j + 1));
}
return result;
}
6.14 估算π
public static void main(String[] args) {
System.out.println("i" + " " + "m(i)");
System.out.println("-------------------");
for (int i = 1; i <= 901; i += 100) {
System.out.printf("%-3d%15.4f\n", i, getResult(i));
}
}
public static double getResult(int i) {
double result = 0;
for (int j = 1; j <= i; j++) {
result = result + Math.pow(-1, j + 1) / (2 * j - 1);
}
result = result * 4;
return result;
}
6.16 一年的天数
public static void main(String[] args) {
System.out.println("年份" + " " + "天数");
System.out.println("-------------------");
for (int i = 2000; i <= 2020; i++) {
System.out.printf("%-4d%14d\n", i, daysOfYear(i));
}
}
public static int daysOfYear(int year) {
if (isLeapYear(year)) {
return 366;
} else return 365;
}
public static boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
6.17 显示0和1构成的矩阵
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个值:");
int n = scanner.nextInt();
printMatrix(n);
}
public static void printMatrix(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(Math.round(Math.random()) + " ");
}
System.out.println();
}
}
6.18 检测密码
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入密码:");
String str = scanner.nextLine();
switch (checkPassword(str)) {
case 0:
System.out.print("密码必须是8位以上!");
break;
case 1:
System.out.print("密码必须只包含字符和数字!");
break;
case 2:
System.out.print("密码必须包含至少两个数字!");
break;
default:
System.out.print("密码检验通过!");
break;
}
}
public static int checkPassword(String pwd) {
int numDigit = 0;
int numLetter = 0;
if (pwd.length() >= 8) {
for (int i = 0; i < pwd.length(); i++) {
if (Character.isDigit(pwd.substring(i, i + 1).charAt(0)) ||
Character.isLetter(pwd.substring(i, i + 1).charAt(0))) {
if (Character.isDigit(pwd.substring(i, i + 1).charAt(0))) {
numDigit++;
}
if (Character.isLetter(pwd.substring(i, i + 1).charAt(0))) {
numLetter++;
}
} else {
return 1;
}
}
if (numDigit >= 2 && numLetter > 0) {
return 3;
} else if (numDigit >= 2 && numLetter == 0) {
return 1;
} else if (numDigit == 0 && numLetter > 0) {
return 1;
} else return 2;
} else {
return 0;
}
}
6.20 字符串中字符的个数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String s = scanner.nextLine();
System.out.println("该字符串中一共含有" + countLetters(s) + "个字母");
}
public static int countLetters(String s) {
int num = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i))) {
num++;
}
}
return num;
}
6.21 电话按键盘
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.nextLine();
System.out.print("对应的数字键盘为:" + changeToNum(str));
}
public static String changeToNum(String str) {
StringBuffer toNumBuffer = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i));
if (ch == 'a' || ch == 'b' || ch == 'c') {
toNumBuffer.append("2");
} else if (ch == 'd' || ch == 'e' || ch == 'f') {
toNumBuffer.append("3");
} else if (ch == 'g' || ch == 'h' || ch == 'i') {
toNumBuffer.append("4");
} else if (ch == 'j' || ch == 'k' || ch == 'l') {
toNumBuffer.append("5");
} else if (ch == 'm' || ch == 'n' || ch == 'o') {
toNumBuffer.append("6");
} else if (ch == 'p' || ch == 'q' || ch == 'r' || ch == 's') {
toNumBuffer.append("7");
} else if (ch == 't' || ch == 'u' || ch == 'v') {
toNumBuffer.append("8");
} else if (ch == 'w' || ch == 'x' || ch == 'y' || ch == 'z') {
toNumBuffer.append("9");
} else if (ch == ' ') {
toNumBuffer.append("0");
} else if (ch == '+') {
toNumBuffer.append("*");
} else {
toNumBuffer.append(str.charAt(i));
}
}
return toNumBuffer.toString();
}
6.23 指定字符的出现次数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一串字符:");
String str = scanner.nextLine();
System.out.print("请输入要计算的字符:");
String strLetter = scanner.nextLine();
char ch = strLetter.charAt(0);
System.out.print(ch + "在" + str + "中出现的次数为:" + count(str, ch) + "次");
}
public static int count(String str, char ch) {
int num = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
num++;
}
}
return num;
}
6.25 将毫秒转换成小时数、分钟数和秒数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入毫秒:");
long ms = scanner.nextLong();
System.out.print("转换后的时间为:" + convertMillis(ms));
}
public static String convertMillis(long millis) {
long totalSecond = millis / 1000;
long hour = totalSecond / 3600;
long min = (totalSecond - (hour * 3600)) / 60;
long second = totalSecond - (hour * 3600) - (min * 60);
return hour + ":" + min + ":" + second;
}
6.26 回文素数
public static void main(String[] args) {
int num = 2;
int count = 0;
while (count < 100) {
if (isPalindrome(num) && isPrime(num)) {
count++;
System.out.printf("%-7d", num);
if (count % 10 == 0) {
System.out.println();
}
}
num++;
}
}
private static boolean isPalindrome(int num) {
int reNum = 0;
int numTmp = num;
while (numTmp != 0) {
reNum = numTmp % 10 + (reNum * 10);
numTmp = numTmp / 10;
}
return num == reNum;
}
private static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
6.27 反素数
public static void main(String[] args) {
int num = 11;
int count = 0;
while (count < 100) {
if (notPalindrome(num) && isPrime(num)) {
count++;
System.out.printf("%-7d", num);
if (count % 10 == 0) {
System.out.println();
}
}
num++;
}
}
private static boolean notPalindrome(int num) {
int reNum = 0;
int numTmp = num;
while (numTmp != 0) {
reNum = numTmp % 10 + (reNum * 10);
numTmp = numTmp / 10;
}
return num != reNum;
}
private static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
int reNum = 0;
while (num != 0) {
reNum = num % 10 + (reNum * 10);
num = num / 10;
}
for (int i = 2; i < reNum; i++) {
if (reNum % i == 0)
return false;
}
return true;
}
6.28 梅森素数
public static void main(String[] args) {
System.out.println("p 2^p-1");
System.out.println("----------------------");
int num;
for (int i = 2; i <= 31; i++) {
num = (int) (Math.pow(2, i) - 1);
if (isPrime(i) && isPrime(num)) {
System.out.printf("%-2d%20d\n", i, num);
}
}
}
private static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
6.29 双素数
public static void main(String[] args) {
for (int i = 2; i <= 998; i++) {
if (isPrime(i) && isPrime(i + 2)) {
System.out.println("(" + i + "," + (i + 2) + ")");
}
}
}
private static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
6.30 双骰子赌博
private static int count = 0;
public static void main(String[] args) {
int num1 = (int) (Math.random() * 6) + 1;
int num2 = (int) (Math.random() * 6) + 1;
System.out.println("你投出了" + num1 + "+" + num2 + "=" + (num1 + num2));
isWin(num1, num2);
System.out.print("总共投掷了" + count + "次");
}
private static void isWin(int num1, int num2) {
int sum = num1 + num2;
if (sum == 2 || sum == 3 || sum == 12) {
System.out.println("你输了!");
count++;
} else if (sum == 7 || sum == 11) {
System.out.println("你赢了!");
count++;
} else {
count++;
int result = 0;
while (result == 0) {
System.out.print("请继续!");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
result = playAgain(num1, num2);
count++;
}
}
}
private static int playAgain(int num1, int num2) {
int sum = num1 + num2;
int num1_new = (int) (Math.random() * 6) + 1;
int num2_new = (int) (Math.random() * 6) + 1;
System.out.println("你投出了" + num1_new + "+" + num2_new + "=" + (num1_new + num2_new));
if (num1_new + num2_new == sum) {
System.out.println("你赢了!");
return 1;
} else if (num1_new + num2_new == 7) {
System.out.println("你输了!");
return 1;
} else {
return 0;
}
}
6.31 信用卡号的合法性
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入16位银行卡号:");
long cardNum = input.nextLong();
if (isValidCard(cardNum)) {
System.out.print("此卡号有效!");
} else {
System.out.print("此卡号无效!");
}
}
private static boolean isValidCard(long cardNum) {
return (oddCount(cardNum) + evenCount(cardNum)) % 10 == 0;
}
private static int oddCount(long cardNum) {
int oddCount = 0;
int odd;
char oddChar;
for (int i = 15; i >= 1; i = i - 2) {
oddChar = String.valueOf(cardNum).charAt(i);
odd = Integer.parseInt(String.valueOf(oddChar));
oddCount = oddCount + odd;
}
return oddCount;
}
private static int evenCount(long cardNum) {
int evenCount = 0;
int even;
int evenNew;
char evenChar;
for (int i = 14; i >= 0; i = i - 2) {
evenChar = String.valueOf(cardNum).charAt(i);
even = Integer.parseInt(String.valueOf(evenChar));
if (even * 2 >= 10) {
evenNew = even * 2 - 9;
} else {
evenNew = even * 2;
}
evenCount = evenCount + evenNew;
}
return evenCount;
}
6.32 骰子的游戏统计
private static int count = 0;
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
startPlay();
}
System.out.print("总共投掷了" + count + "次");
}
private static void startPlay() {
int num1 = (int) (Math.random() * 6) + 1;
int num2 = (int) (Math.random() * 6) + 1;
System.out.println("你投出了" + num1 + "+" + num2 + "=" + (num1 + num2));
isWin(num1, num2);
}
private static void isWin(int num1, int num2) {
int sum = num1 + num2;
if (sum == 2 || sum == 3 || sum == 12) {
System.out.println("你输了!");
count++;
} else if (sum == 7 || sum == 11) {
System.out.println("你赢了!");
count++;
} else {
count++;
int result = 0;
while (result == 0) {
System.out.print("请继续!");
result = playAgain(num1, num2);
count++;
}
}
}
private static int playAgain(int num1, int num2) {
int sum = num1 + num2;
int num1_new = (int) (Math.random() * 6) + 1;
int num2_new = (int) (Math.random() * 6) + 1;
System.out.println("你投出了" + num1_new + "+" + num2_new + "=" + (num1_new + num2_new));
if (num1_new + num2_new == sum) {
System.out.println("你赢了!");
return 1;
} else if (num1_new + num2_new == 7) {
System.out.println("你输了!");
return 1;
} else {
return 0;
}
}
6.35 五边形的面积
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入五边形的边长:");
double side = scanner.nextDouble();
System.out.print("面积为:" + area(side));
}
private static double area(double side) {
return Math.round((5 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 5)) * 100) / 100d;
}
6.36 正多边形的面积
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入多边形的边数:");
int n = scanner.nextInt();
System.out.print("请输入多边形的边长:");
double side = scanner.nextDouble();
System.out.print("面积为:" + area(n, side));
}
private static double area(int n, double side) {
return Math.round((n * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / n)) * 100) / 100d;
}
6.37 格式化整数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int number = scanner.nextInt();
System.out.print("请输入前缀字符串个数:");
int width = scanner.nextInt();
System.out.print("格式化后为:" + format(number, width));
}
private static String format(int number, int width) {
StringBuffer str = new StringBuffer();
for (int i = 1; i <= width - String.valueOf(number).length(); i++) {
str = str.append("0");
}
str.append(String.valueOf(number));
return str.toString();
}
6.38 生成随机字符
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
System.out.print(getRandomUpperCaseLetter() + " ");
if (i % 10 == 0) {
System.out.println();
}
}
for (int i = 1; i <= 100; i++) {
System.out.print(getRandomDigitCharacter() + " ");
if (i % 10 == 0) {
System.out.println();
}
}
}
private static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
private static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
private static char getRandomCharacter(char ch1, char ch2) {
return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}