经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Java基础教程(9)--流程控制
来源:cnblogs  作者:maconn  时间:2018/10/16 9:40:15  对本文有异议

一.分支结构

1.if语句

??if语句会与其后的第一条语句或代码块结合,且只有当判断条件为true时才执行语句或代码块。例如,自行车只有在运动的时候才可以减速,就像下面这样:

  1. void applyBrakes() {
  2. if (isMoving){
  3. currentSpeed--;
  4. }
  5. }

??如果判断条件为false,也就是自行车处于静止状态时,将会跳过if语句后面的语句或代码块。
??如果if语句后只有一条需要执行的语句,既可以使用大括号,也可以不使用。不过按照惯例来说,任何时候都应该使用大括号,这样可以避免有时因为忘记大括号而带来的一些逻辑错误。for、while语句也是同理。

2.if-else语句

??if语句只是指出了当判断条件为true时需要执行的语句。使用if-else语句可以同时指定当判断条件为true和false时应该执行的语句。当自行车没有处于运动状态时,可以简单地输出一条信息:

  1. void applyBrakes() {
  2. if (isMoving){
  3. currentSpeed--;
  4. } else {
  5. System.out.println("The bicycle has already stopped!");
  6. }
  7. }

??下面的程序根据分数来给出对应的等级:

  1. class IfElseDemo {
  2. public static void main(String[] args) {
  3. int testscore = 76;
  4. char grade;
  5. if (testscore >= 90) {
  6. grade = 'A';
  7. } else if (testscore >= 80) {
  8. grade = 'B';
  9. } else if (testscore >= 70) {
  10. grade = 'C';
  11. } else if (testscore >= 60) {
  12. grade = 'D';
  13. } else {
  14. grade = 'F';
  15. }
  16. System.out.println("Grade = " + grade);
  17. }
  18. }

??该程序最终的输出为:

  1. Grade = C

??虽然testscore满足很多条件,例如76>=70和76>=60等,但是,一旦满足了一个条件,就会执行对应的语句(grade = 'C';)并跳过剩余条件。

3.switch语句

??与if和if-else语句不同,switch语句可以有许多可能的执行路径。例如下面的代码将会使用switch语句根据month的值来输出对应的月份:

  1. public class SwitchDemo1 {
  2. public static void main(String[] args) {
  3. int month = 8;
  4. String monthString;
  5. switch (month) {
  6. case 1: monthString = "January";break;
  7. case 2: monthString = "February";break;
  8. case 3: monthString = "March";break;
  9. case 4: monthString = "April";break;
  10. case 5: monthString = "May";break;
  11. case 6: monthString = "June";break;
  12. case 7: monthString = "July";break;
  13. case 8: monthString = "August";break;
  14. case 9: monthString = "September";break;
  15. case 10: monthString = "October";break;
  16. case 11: monthString = "November";break;
  17. case 12: monthString = "December";break;
  18. default: monthString = "Invalid month";break;
  19. }
  20. System.out.println(monthString);
  21. }
  22. }

??该程序将会输出:

  1. August

??switch语句的判断条件是一个变量或表达式,它的类型可以是byte,short,char和int以及它们的包装类(Character,Byte,Short,和Integer),还可以是字符串和枚举类型,case后面是这些类型的字面量。
??default语句用来处理当所有case标签都不满足的情况。break语句用来退出switch块。如果一个case语句最后没有使用break,将会执行下一个case的语句而不进行判断,直到遇到break或switch块结束。下面的例子根据month的值来输出季节:

  1. public class SwitchDemo2 {
  2. public static void main(String[] args) {
  3. int month = 5;
  4. switch(month) {
  5. case 2:
  6. case 3:
  7. case 4: System.out.println("Spring");
  8. case 5:
  9. case 6:
  10. case 7: System.out.println("Summer");
  11. case 8:
  12. case 9:
  13. case 10: System.out.println("Autumn");
  14. case 11:
  15. case 12:
  16. case 1: System.out.println("Winter");
  17. }
  18. }
  19. }

??该程序将会输出:

  1. Summer

??其实无论month的值是5,6还是7,都会输出Summer,因为case 5和case 6都没有break语句,即使匹配到了它们,程序也还是会进入case 7。

二.循环结构

1.while语句和do-while语句

??当判断条件为true时,while语句将会重复执行代码块中的内容,直到判断条件为false。它的语法如下:

  1. while (expression) {
  2. statement(s)
  3. }

??下面的程序使用while循环打印出1~10:

  1. class WhileDemo {
  2. public static void main(String[] args){
  3. int count = 1;
  4. while (count < 11) {
  5. System.out.println("Count is: " + count);
  6. count++;
  7. }
  8. }
  9. }

??可以使用以下while语句实现无限循环:

  1. while (true){
  2. // your code goes here
  3. }

??Java也支持do-while循环,语法如下:

  1. do {
  2. statement(s)
  3. } while (expression);

??do-while循环和while循环之间的区别在于它在执行完代码块中的语句之后进行判断,而不是在循环开始前进行判断。也就是说,循环体中的代码至少会执行一次。下面的程序使用do-while循环打印出1~10:

  1. class DoWhileDemo {
  2. public static void main(String[] args){
  3. int count = 1;
  4. do {
  5. System.out.println("Count is: " + count);
  6. count++;
  7. } while (count < 11);
  8. }
  9. }

2.for循环

??for循环可以控制循环的次数,它的的语法如下:

  1. for (initialization; condition; increment) {
  2. statement(s)
  3. }

??使用for循环时,需要注意:

  • initialization通常用来更初始化计数器,它只在循环开始前执行一次。
  • condition时每一次循环前要判断的条件,一旦条件不满足,循环将结束。
  • increment用来对计数器进行更新,它在每次循环结束后执行。

??下面的程序使用for循环打印出1~10:

  1. class ForDemo {
  2. public static void main(String[] args){
  3. for(int i=1; i<11; i++){
  4. System.out.println("Count is: " + i);
  5. }
  6. }
  7. }

??注意变量i的声明位置。由于它是在初始化表达式中声明的,因此它的范围和生存周期仅在循环内有效。一旦循环结束,变量i将无法访问。
??for循环的三个表达式都是可选的,任意一个都可以为空。下面的语句将会创建一个无限循环:

  1. for ( ; ; ) {
  2. // your code goes here
  3. }

??for循环还有一种用于迭代数组和集合的格式,称为增强型for循环。下面的程序使用增强型for循环来遍历数组:

  1. class EnhancedForDemo {
  2. public static void mainString [] args){
  3. int [] numbers =
  4. {1,2,3,4,5,6,7,8,9,10};
  5. forint itemnumbers){
  6. System.out.println(“Count is:”+ item);
  7. }
  8. }
  9. }

三.中断控制流

1.break

??break语句用于结束当前控制结构,它有两种形式,带标签的break语句和不带标签的break语句。在之前的switch样例中已经见到了不带标签的break语句。还可以使用不带标签的break语句终止for,while或do-while循环,如下面的BreakDemo程序:

  1. class BreakDemo {
  2. public static void main(String[] args) {
  3. int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
  4. int searchfor = 12;
  5. int i;
  6. boolean foundIt = false;
  7. for (i = 0; i < arrayOfInts.length; i++) {
  8. if (arrayOfInts[i] == searchfor) {
  9. foundIt = true;
  10. break;
  11. }
  12. }
  13. if (foundIt) {
  14. System.out.println("Found " + searchfor + " at index " + i);
  15. } else {
  16. System.out.println(searchfor + " not in the array");
  17. }
  18. }
  19. }

??该程序的输出是:

  1. Found 12 at index 4

??不带标签的break语句跳出最内层的循环或分支结构,但带标签的break语句可以跳出标签对应的那个结构。例如:

  1. class BreakWithLabelDemo {
  2. public static void main(String[] args) {
  3. int[][] arrayOfInts = { { 32, 87, 3, 589 },
  4. { 12, 1076, 2000, 8 },
  5. { 622, 127, 77, 955 } };
  6. int searchfor = 12;
  7. int i;
  8. int j = 0;
  9. boolean foundIt = false;
  10. search:
  11. for (i = 0; i < arrayOfInts.length; i++) {
  12. for (j = 0; j < arrayOfInts[i].length;
  13. j++) {
  14. if (arrayOfInts[i][j] == searchfor) {
  15. foundIt = true;
  16. break search;
  17. }
  18. }
  19. }
  20. if (foundIt) {
  21. System.out.println("Found " + searchfor + " at " + i + ", " + j);
  22. } else {
  23. System.out.println(searchfor + " not in the array");
  24. }
  25. }
  26. }

??当找到12时,程序将跳出search对应的for循环。该程序的输出是:

  1. Found 12 at 1, 0

2.continue

??continue跳到循环体的末尾,并执行循环条件的判断。下面的程序统计字母p的出现次数。如果当前字符不是p,则continue语句将跳过循环的其余部分并继续执行下一次循环。如果是 “p”,计数器会加1:

  1. class ContinueDemo {
  2. public static void main(String[] args) {
  3. String searchMe = "peter piper picked a peck of pickled peppers";
  4. int max = searchMe.length();
  5. int numPs = 0;
  6. for (int i = 0; i < max; i++) {
  7. if (searchMe.charAt(i) != 'p')
  8. continue;
  9. numPs++;
  10. }
  11. System.out.println("Found " + numPs + " p in the string.");
  12. }
  13. }

??该程序的输出是:

  1. Found 9 p in the string.

??和break一样,continue也分为带标签的continue语句和不带标签的continue语句。带标签的continue语句将会结束当前的循环并开始下一次标签对应的循环。下面的程序使用带标签的continue和break语句来判断一个字符串是否包含另一个字符串:

  1. class ContinueWithLabelDemo {
  2. public static void main(String[] args) {
  3. String searchMe = "Look for a substring in me";
  4. String substring = "sub";
  5. boolean foundIt = false;
  6. int max = searchMe.length() - substring.length();
  7. test:
  8. for (int i = 0; i <= max; i++) {
  9. int n = substring.length();
  10. int j = i;
  11. int k = 0;
  12. while (n-- != 0) {
  13. if (searchMe.charAt(j++) != substring.charAt(k++)) {
  14. continue test;
  15. }
  16. }
  17. foundIt = true;
  18. break test;
  19. }
  20. System.out.println(foundIt ? "Found it" : "Didn't find it");
  21. }
  22. }

??该程序的输出是:

  1. Found it

3.return

??最后一个可以中断控制流的语句是return语句,它可以从当前的方法中退出。return语句有两种形式,使用返回值和不使用返回值。如果要返回一个值,只需要将值或表达式放在return关键字后面。例如:

  1. return ++count;

??返回值的数据类型必须与方法声明的返回值的类型匹配。使用没有返回值的return语句时,方法的返回值类型必须声明为void,例如:

  1. return;
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号