Java 常用循环总结
一,序言
Java 中常用的循环都有哪些呢?
我们熟知的循环主要有就三种:
(1)while;
(2) do…while;
(3) for;其他的还有增强for,当然还有常用 break,continue 关键字.
今天我们一起来将这些进行总结一下:
二, 详情
1,while
While 是最基本的循环,结构为:
While(布尔表达式){
//循环内容
}
只要布尔表达式成了, 循环就会一直跑下去.
例子:
Public class Test{
Public static void main(String args[]){
Int x=30;
While(x<50){
System.out.print(“value of x is:”+x);
System.out.print(“\n”);
}
}
}
以上实例结果如下:
Value of x is: 30
Value of x is:31
Value of x is:32
Value of x is:33
,,,,,,持续到49
2,do while
对于 do while, 如果条件不满足, 则不能进入循环,但有时候我们需要即使不满足条件,也至少要执行一次.
Do while 和 while 的区别是: do while 循环至少会执行一次.
Do{
//代码语句.
} while( 布尔表达式);
注意:布尔表达式是在循环体的后面,所以语句块在检查布尔表达式之前已经执行了.如果布尔表达式值为 true, 则语句块会一直执行下去直到为 false.
例子:
Public static void main(String args[]){
Int x=1;
Do{
System.out.print(“value of x is :”+x);
X++;
System.out.print(“\n”);
}while(x<5);
}
以上编译结果如下:
value of x is:1
value of x is:2
value of x is:3
value of x is:4
3,for
我们都知道, 所有循环的都可以用 while, do while,但是 java 提供了更加简单的循环结构: for
For 循环执行的次数是在执行前就确定的.语法格式如下:
For(初始化;布尔表达式;更新){
//代码语句块.
}
注意:
(1)for 循环最新执行初始化步骤.可以声明一种类型,但是初始化一个或多个循环控制变量, 也可以是空语句.
(2)检查布尔表达式的值,如果为 true,循环体被执行,如果是 false, 循环终止,开始执行循环体后面的语句块.
(3)执行一次循环后,更新循环控制变量.
(4)再次检查布尔表达式,循环执行上面的过程.
例子:
Public static void main(String args[]){
For(int x=10;x<15;x=x+1){
System.out.print(“value of x is:”+x);
System.out.print(“\n”);
}
}
以上编译结果如下:
value of x is:10
value of x is:11
value of x is:12
value of x is:13
value of x is:14
4,增强 for
在 java1.5之后, 除了上面简单的 for 循环, 又引入了增强 for 循环,格式如下:
For(声明语句: 表达式){
//代码语句块
}
声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
例子:
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
以上编译结果如下:
10,20,30,40,50,
James,Larry,Tom,Lacy,
5,关键字: break
什么是 break 关键字?
Break 主要是在循环或 switch 语句中,用来跳出整个语句块的.
Break 跳出最里面层的循环,并且继续执行循环下面的语句.
例子:
Public static void main(String args[])[
Int[] numbers={1,2,3,4,5,6};
For(int x:numbers){
If(x==4){
Break;
}
System.out.print(x);
System.out.print(“\n”);
}
}
以上编译结果如下:
1
2
3
6,关键字 continue
Break 是跳出循环或者switch 语句, 那么如果要继续执行语句用什么关键字呢?
Continue 适用任何循环控制结构中,作用是立刻调到下一次循环迭代中.
在 for 循环中, continue 语句程序让程序立即跳到更新语句.
在 while 或 do …while,让程序立刻跳到布尔表达式的判断语句中.
例子:
public static void main(String args[]) {
int [] numbers = {1, 2, 3, 4, 5,6,7};
for(int x : numbers ) {
if( x == 3 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
以上例子编译结果如下:
1
2
4
5
6
7
三,总结
循环的总结起来一共就三种,在真正的运用中,其实增强fo还用的更加的多,在用循环语句过程中,还需要注意思考如果让性能更加的高效,已经后期能更好的优化等问题.