第四章 控制执行流程
关键字包括if-else、while、do-while、for、return、break、switch,不支持goto
4.1 true和false
- ==或者是!=,这个没啥可说的
4.2 if-else
- if-else是可选的,意思就是我们可以只有if,也可以if-else都有
- 这在编程中是很常见的,注意if和if-else的执行区别,if执行完继续向下,if-else执行了其中一个另一个就不执行了
4.3 迭代
while、do-while、for用来控制循环
4.3.1 do-while
- 无论是否是true或者是false,起码都会执行一次,确实也是,实际开发中while用的更多一些
4.3.2 for
- for (initialization; Boolean-expression; step)
- for(初始化表达式;布尔表达式;步进运算)
- for(int i = 0; i < 3; i++)
- 三个值都可以为空
练习1、打印1到100的值
public class E01_To100 { public static void main(String[] args) { for(int i = 1; i <= 100; i++) { System.out.print(i + " "); } } }
练习2、产生25个int型随机数,并使用if-else来分类
public class E02_RandomInts { static Random r = new Random(47); public static void compareRand() { int a = r.nextInt(); int b = r.nextInt(); System.out.println("a = " + a + ", b = " + b); if(a < b) System.out.println("a < b"); else if(a > b) System.out.println("a > b"); else System.out.println("a = b"); } public static void main(String[] args) { for(int i = 0; i < 25; i++) compareRand(); } }
练习3、在练习2的基础上修改,用while循环,使用键盘中断
public class E03_RandomInts2 { public static void main(String[] args) { while(true) E02_RandomInts.compareRand(); } }
练习4、使用两个嵌套的for循环和%操作符打印素数
public class E04_FindPrimes { public static void main(String[] args) { int max = 100; // Get the max value from the command line, // if the argument has been provided: if(args.length != 0) { max = Integer.parseInt(args[0]); } for(int i = 1; i < max; i++) { boolean prime = true; for(int j = 2; j < i; j++) { if(i % j == 0) { prime = false; } } if(prime) { System.out.print(i + " "); } } } }
更清晰的一个打印素数的写法,将第二个for循环分离出来
public class Test { public static void main(String[] args) { int count = 0; for (int i = 2; i <= 100; i++) { //从2开始 if(isSuShu(i)){ //判断是否为素数 System.out.print(i+" "); //打印素数 count ++; } } System.out.println("\n"); System.out.println("共有"+count+"个"); } /** * 判断一个整数是不是素数的方法 * @param number * @return */ public static boolean isSuShu(int number){ for(int i=2; i<number; i++){ //从2开始 if(number % i == 0){ //判断是否能除尽 return false; //返回false } } return true; //返回true }
练习5、用三元操作符和按位操作符来显示二进制的1和0
public class E05_BitwiseOperators2 { private static void toBinaryString(int i) { char[] buffer = new char[32]; int bufferPosition = 32; do { buffer[--bufferPosition] = ((i & 0x01) != 0) ? '1' : '0'; i >>>= 1; } while (i != 0); for(int j = bufferPosition; j < 32; j++) printnb(buffer[j]); print(); } public static void main(String[] args) { int i1 = 0xaaaaaaaa; int i2 = 0x55555555; printnb("i1 = "); toBinaryString(i1); printnb("i2 = "); toBinaryString(i2); printnb("~i1 = "); toBinaryString(~i1); printnb("~i2 = "); toBinaryString(~i2); printnb("i1 & i1 = "); toBinaryString(i1 & i1); printnb("i1 | i1 = "); toBinaryString(i1 | i1); printnb("i1 ^ i1 = "); toBinaryString(i1 ^ i1); printnb("i1 & i2 = "); toBinaryString(i1 & i2); printnb("i1 | i2 = "); toBinaryString(i1 | i2); printnb("i1 ^ i2 = "); toBinaryString(i1 ^ i2); } }
4.3.3 逗号操作符
唯一用到逗号操作符的是在for循环的控制表达式中,可以使用一系列逗号分隔的语句
4.4 Foreach语法
更简洁的用于数组和容器
for(String s : list) { System.out.println(s); }
4.5 return
- 一方面指定一个方法返回什么值,另一方面导致当前的方法退出,并返回那个值
- 如果是void修饰的,方法结尾会有一个隐式的return,执行了return会跳出当前方法
练习6、判断一个数是否是在begin和end之间
public class E06_RangeTest { static boolean test(int testval, int begin, int end) { boolean result = false; if(testval >= begin && testval <= end) result = true; return result; } public static void main(String[] args) { System.out.println(test(10, 5, 15)); System.out.println(test(5, 10, 15)); System.out.println(test(5, 5, 5)); } }
4.6 break和continue
- break是跳出当前整个循环
- continue是跳出当前此项的循环,继续执行下一项的循环
练习7、使用break在打印到99退出,尝试使用return来达到相同的目的
public class E07_To98 { public static void main(String[] args) { for(int i = 1; i <= 100; i++) { if(i == 99) break; System.out.print(i + " "); } } }
4.7 臭名昭著的goto
1、goto就是乱跳,跳到这,跳到那
2、Java中没有goto,但是可以实现类似的功能,那就是label,很少用,不读到这本书我还不知道Java有这个功能
3、通过break和continue来实现:
- 带标签的continue会退回到标签位置,并且重新执行标签后的循环
- 带标签的break会中断并跳出标签所指的循环,不会再执行标签后的循环
尽量不要使用标签,随着标签的增多,产生的错误也会越来越多,会使得程序难以分析
4.8 switch
- 实现多路选择的一种干净利落的方法,需要一个选择因子,去和switch中的每个值去比较
- 选择因子必须是int或char那样的整数值,Java7之后开始支持String
- 每个case都会有一个break结尾,其实这个可选的,我们可以控制
- 如果都匹配不到就执行default语句
练习8:switch开关语句,有break和没有break的区别
public class E08_SwitchDemo { public static void main(String[] args) { for(int i = 0; i < 7; i++) { switch(i) { case 1: System.out.println("case 1"); break; case 2: System.out.println("case 2"); break; case 3: System.out.println("case 3"); break; case 4: System.out.println("case 4"); break; case 5: System.out.println("case 5"); break; default: System.out.println("default"); } } } } public class E08_SwitchDemo2 { public static void main(String[] args) { for(int i = 0; i < 7; i++) { switch(i) { case 1: System.out.println("case 1"); case 2: System.out.println("case 2"); case 3: System.out.println("case 3"); case 4: System.out.println("case 4"); case 5: System.out.println("case 5"); default: System.out.println("default"); } } } }
练习9、斐波那契数列
此解法是递归解法,还有正常的直接赋值,使用数组法 public class E09_Fibonacci { static int fib(int n) { if (n <= 2) return 1; return fib(n-1) + fib(n-2); } public static void main(String[] args) { // Get the max value from the command line: int n = Integer.parseInt(args[0]); if(n < 0) { System.out.println("Cannot use negative numbers"); return; } for(int i = 1; i <= n; i++) System.out.print(fib(i) + ", "); } }
练习10、吸血鬼数字
// 这个算法大体的思想如下 // 定义两个数组,一个保存那两个数,另一个保存乘积之后的数 // 通过for循环,去遍历 // 最后将这两个数组去比较,如果4个数是一样的,相同的次数是4次,也就是count==4 // 那么这个数就是吸血鬼数字 public class E10_Vampire { public static void main(String[] args) { int[] startDigit = new int[4]; int[] productDigit = new int[4]; for(int num1 = 10; num1 <= 99; num1++) for(int num2 = num1; num2 <= 99; num2++) { // Pete Hartley's theoretical result: // If x·y is a vampire number then // x·y == x+y (mod 9) if((num1 * num2) % 9 != (num1 + num2) % 9) continue; int product = num1 * num2; startDigit[0] = num1 / 10; startDigit[1] = num1 % 10; startDigit[2] = num2 / 10; startDigit[3] = num2 % 10; productDigit[0] = product / 1000; productDigit[1] = (product % 1000) / 100; productDigit[2] = product % 1000 % 100 / 10; productDigit[3] = product % 1000 % 100 % 10; int count = 0; for(int x = 0; x < 4; x++) for(int y = 0; y < 4; y++) { if(productDigit[x] == startDigit[y]) { count++; productDigit[x] = -1; startDigit[y] = -2; if(count == 4) System.out.println(num1 + " * " + num2 + " : " + product); } } } } }
总结
本章介绍了大多数编程语言都具有的基本特性,运算、操作符优先级、类型转换和循环等等