【Java基础】流程控制语句

怼烎@ 2024-03-26 11:05 106阅读 0赞

流程控制语句

判断语句

if

主要是判断true /false

  1. int score=80;
  2. if(score>=80){
  3. System.out.println("优秀");
  4. }else if(score>=60){
  5. System.out.println("及格");
  6. }else{
  7. System.out.println("不及格");
  8. }
switch
  1. int month = 8;
  2. String monthString;
  3. switch (month) {
  4. //switch表达式不能为空
  5. case 1: monthString = "January";
  6. break;
  7. case 2: monthString = "February";
  8. break;
  9. case 3: monthString = "March";
  10. break;
  11. case 4: monthString = "April";
  12. break;
  13. case 5: monthString = "May";
  14. break;
  15. case 6: monthString = "June";
  16. break;
  17. case 7: monthString = "July";
  18. break;
  19. case 8: monthString = "August";
  20. break;
  21. case 9: monthString = "September";
  22. break;
  23. case 10: monthString = "October";
  24. break;
  25. case 11: monthString = "November";
  26. break;
  27. case 12: monthString = "December";
  28. break;
  29. default: monthString = "Invalid month";
  30. break;//最后一个break,不是必须的,但建议写上
  31. }
  32. System.out.println(monthString);

循环语句

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

do语句至少执行一次

for循环
  1. for (initialization; termination;increment) {
  2. statement(s)
  3. }

initialization表达式初始化循环; 在循环开始时执行一次

termination循环终止条件

increment增量,每次循环最后被调用

增强for循环(推荐)
  1. int[] numbers =
  2. {
  3. 1,2,3,4,5,6,7,8,9,10};
  4. for (int item : numbers) {
  5. System.out.println("Count is: " + item);
  6. }

分支语句

break
switch
循环中

跳出循环

跳出内层循环

带标签的break
  1. label://label可以自定义,label1....
  2. for (int i = 0; i < 3; i++) {
  3. for (int j = 0; j < 3; j++) {
  4. if(j==2){
  5. break label;//直接跳出外层循环
  6. }
  7. System.out.println("内");
  8. }
  9. System.out.println("外");
  10. }
continue

跳过该次循环的剩余部分,继续执行下一次循环

跳过内层循环

带标签的continue

跳过label标签的大循环

  1. label:
  2. for (int i = 0; i < 3; i++) {
  3. for (int j = 0; j < 3; j++) {
  4. if(j==2){
  5. continue label;
  6. }
  7. System.out.println("内");
  8. }
  9. System.out.println("外");
  10. }
return

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读