练习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);}}