基本流程控制for,break,switch

Java5引入了一种更为简洁的for语法,可以用于数组和容器。

for-in语句自动生成每一项元素。

public class ForInFloat {
    public static void main(String[] args) {

        Random rand = new Random(47);
        float[] f = new float[10];
        for (int i = 0; i < 10; i++) {
            f[i] = rand.nextFloat();
        }

    }
}
public class ForInString {
    public static void main(String[] args) {
        for(char c : "hello,how are you ?".toCharArray())
            System.out.print(c + " ");
    }
}

逗号操作符

逗号操作符不是逗号分隔符,逗号分隔符用来分隔声明和函数的不同参数,而Java里唯一用到逗号操作符的地方就是for循环的控制结构。

通过使用逗号操作符,可以在for语句里定义多个变量,但它们必须是相同的类型。

public class CommaOperation {
    public static void main(String[] args) {
        for(int i = 1, j = i + 10; i < 5; i++, j = i * 2){
            System.out.println("i = " + i + " j = " + j);
        }
    }
}

break和continue

public class BreakAndContinue {
  public static void main(String[] args) {
    for(int i = 0; i < 100; i++) {        // [1]
      if(i == 74) break; // Out of for loop
      if(i % 9 != 0) continue; // Next iteration
      System.out.print(i + " ");  //打印 9 的倍数 0 9 18 ...
    }
    System.out.println();
    // Using for-in:
    for(int i : range(100)) {             // [2]
      if(i == 74) break; // Out of for loop
      if(i % 9 != 0) continue; // Next iteration
      System.out.print(i + " ");
    }
    System.out.println();
    int i = 0;
    // An "infinite loop":
    while(true) {                         // [3]
      i++;
      int j = i * 27;
      if(j == 1269) break; // Out of loop
      if(i % 10 != 0) continue; // Top of loop
      System.out.print(i + " ");
    }
  }
}

标签

标签是以冒号结尾的标识符:

label1:

在Java中,放置标签的唯一地方是正好在迭代语句之前。"正好"的意思是,不要在标签和迭代之间插入任何语句。用于中断嵌套循环,直接跳转到标签所在位置。

while循环里的带标签的break和continue:

continue break + 标签名

注意,当i = 5 时,break退出内层循环到外层循环,执行:System.out.println("Outer while loop");

public class LabeledWhile {
  public static void main(String[] args) {
    int i = 0;
    outer:
    while(true) {
      System.out.println("Outer while loop");
      while(true) {
        i++;
        System.out.println("i = " + i);
        if(i == 1) {
          System.out.println("continue");
          continue;
        }
        if(i == 3) {
          System.out.println("continue outer");
          continue outer;
        }
        if(i == 5) {
          System.out.println("break");
          break;
        }
        if(i == 7) {
          System.out.println("break outer");
          break outer;
        }
      }
    }
  }
}

带标签的break和带标签的continue可用于for循环:

public class LabeledFor {
  public static void main(String[] args) {
    int i = 0;
    outer: // Can't have statements here
    for(; true ;) { // infinite loop
      inner: // Can't have statements here
      for(; i < 10; i++) {
        System.out.println("i = " + i);
        if(i == 2) {
          System.out.println("continue");
          continue;
        }
        if(i == 3) {
          System.out.println("break");
          i++; // Otherwise i never
               // gets incremented.
          break;
        }
        if(i == 7) {
          System.out.println("continue outer");
          i++; // Otherwise i never
               // gets incremented.
          continue outer;
        }
        if(i == 8) {
          System.out.println("break outer");
          break outer;
        }
        for(int k = 0; k < 5; k++) {
          if(k == 3) {
            System.out.println("continue inner");
            continue inner;
          }
        }
      }
    }
    // Can't break or continue to labels here
  }
}

switch

switch有时也叫作选择语句。根据整数表达式的值,switch语句从多个代码片段中选择一个去执行。

方法外的:

public class VowelsAndConsonants {
  public static void main(String[] args) {
    Random rand = new Random(47);
    for(int i = 0; i < 100; i++) {
      int c = rand.nextInt(26) + 'a';
      System.out.print((char)c + ", " + c + ": ");
      switch(c) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u': System.out.println("vowel");
                  break;
        case 'y':
        case 'w': System.out.println("Sometimes vowel");
                  break;
        default:  System.out.println("consonant");
      }
    }
  }
}

方法里的switch:(摘自抽象类 模板设计模式)

将参数作为选择器

public void commond(int flags){
	  switch(flags){
		case EAT:
			this.eat();
			break;
		case SLEEP:
			this.sleep();
			break;
		case WORK:
			this.work();
			break;
		case EAT + SLEEP:
			this.eat();
			this.sleep();
			break;
		case SLEEP + WORK:
			this.sleep();
			this.work();
			break;
		default:
			break;
		}
	}

字符串作为选择器

Java7及以后的版本中,字符串也可以用作选择器。

字符串常量.equals(字符串变量);

public class StringSwitch {
  public static void main(String[] args) {
    String color = "red";
    // Old way: using if-then
    if("red".equals(color)) {
      System.out.println("RED");
    } else if("green".equals(color)) {
      System.out.println("GREEN");
    } else if("blue".equals(color)) {
      System.out.println("BLUE");
    } else if("yellow".equals(color)) {
      System.out.println("YELLOW");
    } else {
      System.out.println("Unknown");
    }
    // New way: Strings in switch
    switch(color) {
      case "red":
        System.out.println("RED");
        break;
      case "green":
        System.out.println("GREEN");
        break;
      case "blue":
        System.out.println("BLUE");
        break;
      case "yellow":
        System.out.println("YELLOW");
        break;
      default:
        System.out.println("Unknown");
        break;
    }
  }
}

小混合switch

public class Switch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        for (Color col : Color.values()) {
            System.out.print(col + " ");
        }
        System.out.println("\n" + "input a color from enum : ");
        String color = scanner.next();

        switch(color) {
            case "red":
                System.out.println("RED");
                break;
            case "green":
                System.out.println("GREEN");
                break;
            case "blue":
                System.out.println("BLUE");
                break;
            case "yellow":
                System.out.println("YELLOW");
                break;
            default:
                System.out.println("Unknown");
                break;
        }
    }
    enum Color {
        red, green, blue, yellow;
    }

注意遍历枚举值的方法:

for (Color col : Color.values()) {
            System.out.print(col + " ");
        }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值