《Java编程思想》第四章习题答案

embedded/2024/11/20 20:42:00/

练习1:(1) 写一个程序,打印从1到100的值。

答案:

package thinkinginjava.chapterfour;public class ChapterFourExerciseOne {public static void main(String[] args) {int index = 0;while(++index <= 100) {System.out.print(index + " ");}}}

练习2:(2) 写一个程序,产生25个int类型的随机数。对于每一个随机值,使用if-else语句来将其分类为大于、小于,或等于紧随它而随机生成的值。

答案:

package thinkinginjava.chapterfour;import java.util.Random;public class ChapterFourExerciseTwo {public static final int ARRAY_SIZE = 25;public static void main(String[] args) {int[] arr= generateRandomArray(ARRAY_SIZE);for (int i = 0; i < ARRAY_SIZE; i++) {if(i == ARRAY_SIZE - 1) {System.out.println(arr[i] + "is the last element");break;}System.out.println(i + " pair random numbers: ");compare(arr[i], arr[i+1]);System.out.println();}}public static int[] generateRandomArray(int size) {Random rand = new Random();int[] arr = new int[size];for (int i = 0; i < size; i++) {arr[i] = rand.nextInt(100);}return arr;}public static void compare(int numberOne, int numberTwo) {if (numberOne == numberTwo) {System.out.println(numberOne + " equals " + numberTwo);} else if (numberOne < numberTwo) {System.out.println(numberOne + " less than " + numberTwo);}else{System.out.println(numberOne + " greater than " + numberTwo);}}}

练习3:(1) 修改练习2,把代码用一个while无限循环包括起来。然后运行它直至用键盘中断其运行(通常是通过按Ctrl+C)。

答案:

package thinkinginjava.chapterfour;import java.util.Random;public class ChapterFourExerciseThree {public static final int ARRAY_SIZE = 25;public static void main(String[] args) {int[] arr= generateRandomArray(ARRAY_SIZE);while(true) {for (int i = 0; i < ARRAY_SIZE; i++) {if (i == ARRAY_SIZE - 1) {System.out.println(arr[i] + "is the last element");break;}System.out.println(i + " pair random numbers: ");compare(arr[i], arr[i + 1]);System.out.println();}}}public static int[] generateRandomArray(int size) {Random rand = new Random();int[] arr = new int[size];for (int i = 0; i < size; i++) {arr[i] = rand.nextInt(100);}return arr;}public static void compare(int numberOne, int numberTwo) {if (numberOne == numberTwo) {System.out.println(numberOne + " equals " + numberTwo);} else if (numberOne < numberTwo) {System.out.println(numberOne + " less than " + numberTwo);}else{System.out.println(numberOne + " greater than " + numberTwo);}}}

练习4:(3) 写一个程序,使用两个嵌套的for循环和取余操作符(%)来探测和打印素数(只能被其自身和1整除,而不能被其他数字整除的整数)。

答案:

package thinkinginjava.chapterfour;public class ChapterFourExerciseFour {public static final int MAX_NUM = 100;public static void main(String[] args) {for (int i = 2; i < MAX_NUM; i++) {if(isPrimeNum(i)){System.out.println(i + " is prime number");}}}public static boolean isPrimeNum(int num) {for (int i = 2; i < Math.abs(num); i++) {if (num % i == 0) {return false;}}return true;}}

练习5:(4) 重复第3章中的练习10,不要用Integer.toBinaryString()方法,而是用三元操作符和按位操作符来显示二进制的1和0。

答案:

package thinkinginjava.chapterfour;public class ChapterFourExerciseFive {public static final int INT_BIT_NUM = 32;public static void main(String[] args) {int valueOne = 0x55555555;  // binary 01010101010101010101010101010101int valueTwo = 0xAAAAAAAA;  // binary 10101010101010101010101010101010System.out.println("valueOne in binary: " + intToBinaryString(valueOne));System.out.println("valueTwo in binary: " + intToBinaryString(valueTwo));int andResult = valueOne & valueTwo;System.out.println("andResult in binary: " + intToBinaryString(andResult));int orResult = valueOne | valueTwo;System.out.println("orResult in binary: " + intToBinaryString(orResult));int xorResult = valueOne ^ valueTwo;System.out.println("xorResult in binary: " + intToBinaryString(xorResult));int notResultOne = ~valueOne;int notResultTwo = ~valueTwo;System.out.println("notResultOne in binary: " + intToBinaryString(notResultOne));System.out.println("notResultTwo in binary: " + intToBinaryString(notResultTwo));System.out.println("andResult in hexdecimal: 0x" + Integer.toHexString(andResult));System.out.println("orResult in hexdecimal: 0x" + Integer.toHexString(orResult));System.out.println("xorResult in hexdecimal: 0x" + Integer.toHexString(xorResult));System.out.println("notResultOne in hexdecimal: 0x" + Integer.toHexString(notResultOne));System.out.println("notResultTwo in hexdecimal: 0x" + Integer.toHexString(notResultTwo));}public static String intToBinaryString(int number) {String str = "";for (int i = INT_BIT_NUM - 1; i > 0; i--) {str += ((number >> i) & 1) == 1 ? '1' : '0';}return str;}
}

练习6:(2) 修改前两个程序中的两个test()方法,让它们接受两个额外的参数begin和end,这样在测试testval时将判断它是否在begin和end之间(包括begin和end)的范围内。

答案:

package thinkinginjava.chapterfour;public class ChapterFourExerciseSix {public static boolean test(int testval, int begin, int end) {boolean result = testval >= begin && testval <= end;if(result) {System.out.println(testval + " is within the range[" + begin + ", " + end + "]");}else {System.out.println(testval + " is out of the range[" + begin + ", " + end + "]");}return result;}public static void main(String[] args) {test(15,10,20);}}

练习7:(1) 修改本章练习1,通过使用break关键词,使得程序在打印到99时退出。然后尝试使用return来达到相同的目的。

答案:

package thinkinginjava.chapterfour;public class ChapterFourExerciseSeven {public static void main(String[] args) {int index = 0;while(++index <= 100) {System.out.print(index + " ");if(index == 99){break;}}System.out.println();index = 0;while(++index <= 100) {System.out.print(index + " ");if(index == 99){return;}}}}

练习8:(2) 写一个switch开关语句,为每个case打印一个消息。然后把这个switch放进for循环来测试每个case。先让每个case后面都有break,测试一下会怎样;然后把break删了,看看会怎样。

答案:

package thinkinginjava.chapterfour;public class ChapterFourExerciseEight {public static final int MAX_INDEX = 4;public static void main(String[] args) {testSwitchWithBreak();testSwitchWithOutBreak();}public static void testSwitchWithBreak(){for (int i = 0; i <= MAX_INDEX ; i++) {System.out.println("Test case for i = " + i);switch(i){case 1:System.out.println("Case 1: i is 1");break;case 2:System.out.println("Case 2: i is 2");break;case 3:System.out.println("Case 3: i is 3");break;case 4:System.out.println("Case 4: i is 4");break;default:System.out.println("Default case: i is not 1, 2, 3 or 4");}System.out.println();}}public static void testSwitchWithOutBreak(){for (int i = 0; i <= MAX_INDEX ; i++) {System.out.println("Test case for i = " + i);switch(i){case 1:System.out.println("Case 1: i is 1");case 2:System.out.println("Case 2: i is 2");case 3:System.out.println("Case 3: i is 3");case 4:System.out.println("Case 4: i is 4");default:System.out.println("Default case: i is not 1, 2, 3 or 4");}System.out.println();}}}

练习9:(4) 一个斐波那契数列是由数字1、1、2、3、5、8、13、21、34等等组成的,其中每一个数字(从第三个数字起)都是前两个数字的和。创建一个方法,接受一个整数参数,并显示从第一个元素开始总共由该参数指定的个数所构成的所有斐波那契数字。例如,如果运行java Fibonacci 5(其中Fibonacci是类名),那么输出就应该是1、1、2、3、5。

答案:

package thinkinginjava.chapterfour;import java.util.ArrayList;
import java.util.List;public class ChapterFourExerciseNine {public static void main(String[] args) {fibonacci(8);}public static void fibonacci(int n) {List<Integer> fibonacciList = new ArrayList<Integer>();int preOneNumber = 1;int preTwoNumber = 1;fibonacciList.add(preTwoNumber);fibonacciList.add(preOneNumber);int currentNumber = 0;for (int i = 3; i <= n; i++) {currentNumber = preOneNumber + preTwoNumber;preTwoNumber = preOneNumber;preOneNumber = currentNumber;fibonacciList.add(currentNumber);}for(Integer i : fibonacciList) {System.out.print(i + " ");}}}

练习10:(5) 吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的,例如,下列数字都是”吸血鬼“数字:

1260 = 12 * 60

1827 = 21 * 87

2187 = 27 * 81

写一个程序,找出4位数的所有吸血鬼数字(Dan Forhan推荐)。

答案:

package thinkinginjava.chapterfour;import java.util.Arrays;public class ChapterFourExerciseTen {public static void main(String[] args) {System.out.println("4-digit vampire numbers list:");findVampireNumbers();}public static void findVampireNumbers() {for (int number  = 1000; number < 9999; number++) {if(isVampire(number)) {System.out.println(number);}}}public static boolean isVampire(int number) {String numberStr = String.valueOf(number);if(numberStr.equals("00")){return false;}for (int i = 10; i <= 99; i++) {if(number % i == 0){int j = number / i;if(j >= 10 && j <= 99){if(isVampireComponents(numberStr, i, j))return true;}}}return false;}public static boolean isVampireComponents(String numberStr, int i, int j) {String combinedStr = String.valueOf(i) + String.valueOf(j);char[] numberArray = numberStr.toCharArray();char[] combinedArray = combinedStr.toCharArray();Arrays.sort(combinedArray);Arrays.sort(numberArray);return Arrays.equals(combinedArray, numberArray);}}


http://www.ppmy.cn/embedded/139170.html

相关文章

c++学习第三天

创作过程中难免有不足&#xff0c;若您发现本文内容有误&#xff0c;恳请不吝赐教。 提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 一、内联函数 1.铺垫 #include<iostream>//实现一个ADD的宏函数 //#define ADD(x, y) xy //错解1 //#defin…

HbuilderX 插件开发-模板创建

实现思路 使用HbuilderX 打开某个文档时右键点击的时候获取当前打开的文档内容使用 API 替换为自己的模板 示例 package.json {"id": "SL-HbuilderX-Tool","name": "SL-HbuilderX-Tool","description": "快速创建h…

linux配置动态ip

在CentOS中配置动态IP 找到你的网络接口名称&#xff0c;通常是eth0或ens33等&#xff0c;编辑对应的配置文件。这些文件通常位于/etc/sysconfig/network-scripts/目录下&#xff0c;并以ifcfg-开头。 例如&#xff0c;如果你的接口名称是eth0&#xff0c;配置文件将是ifcfg-…

每天五分钟机器学习:支持向量机算法数学基础之核函数

本文重点 从现在开始,我们将开启支持向量机算法的学习,不过在学习支持向量机算法之前,我们先来学习一些支持向量机所依赖的数学知识,这会帮助我们更加深刻的理解支持向量机算法,本文我们先来学习核函数。 定义 核函数(Kernel Function)是一种在支持向量机(SVM)、高…

dotnet:依赖注入

依赖注入的基本概念 依赖&#xff1a;一个类依赖于另一个类或接口来完成其功能。注入&#xff1a;依赖项由外部提供给类&#xff0c;而不是由类自己创建。 builder.Services.AddScoped<IMyDependency, MyDependency>(); 这行代码使用 AddScoped 方法将 IMyDependency 接…

OpenCPN中的GTK版本及调试信息

1:开启GTK的调试信息 export GDK_DEBUG=all root@rk3568-buildroot:/home/corey/opencpn/opencpnbuildroot/OpenCPN/build_wxWidgets3.3.2/install/bin# ./opencpn Gdk-Message: 00:43:27.823: Trying wayland backend Gdk-Message: 00:43:27.824: opening display Gdk-Mes…

Spring Boot 2.x 和 Druid 多数据源整合 dm

参考链接 SpringBoot alibaba druid 语雀 Home alibaba/druid Wiki GitHub druid/druid-spring-boot-starter at master alibaba/druid GitHub 使用 1&#xff09;添加依赖 <!-- druid --> <dependency><groupId>com.alibaba</groupId><a…

python pytorch 加载MNIST训练集,解释

def data_generator(root, batch_size): # 加载MNIST训练集&#xff0c;指定根目录&#xff0c;设置为训练模式&#xff0c;如果数据不存在则下载 train_set datasets.MNIST(rootroot, trainTrue, downloadTrue, # 对图像进行预处理&a…