Day05
增强for循环
java5 引入一种主要用于数组或集合的增强型for循环。
语法格式:
for(声明语句:表达式){
代码句子;
}
声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此事数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
public class Study07 {
public static void main(String[] args) {
int[] numbers ={1,2,3};//定义一个数组
//遍历数组的元素
for (int a : numbers){
System.out.println(a);
}
}
}
break continue
break在任何循环语句的主体部分,均可用break控制循环的流程,break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)
continue语句在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。
代码示例:
public class Study08 {
public static void main(String[] args) {
int a = 0;
while (a <= 100) {
a++;
if (a >= 30) {
break;//终止循环
}
System.out.println(a);
}
System.out.println("==========");
test(a);//调用下面创建的方法test
}
//创建一个方法test
public static void test(int a) {
a=0;
while (a <= 100) {
a++;
if (a % 5 == 0) {
continue;//跳出此次循环
}
System.out.println(a);
}
}
}
小练习
打印一个三角形:
public class Study09 {
public static void main(String[] args) {
for (int a = 1 ;a<=5;a++){
for (int b= 5 ; b>=a;b--){
System.out.print(" ");
}
for(int c = 1 ; c <=2*a-1; c++){
System.out.print("*");
}
System.out.println("");
}
}
}