循环结构
while循环 do…while循环 for循环 在java5中引入了一种主要用于数组的增强型for循环。
while循环
while是最基本的循环,结构为
while ( 布尔表达式) {
}
只要布尔表达式为true,循环就会一直执行下去。 我们大多数情况下是会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环。 少部分情况需要循环一直执行,比如服务器的请求响应监听等。 循环条件一直为true就会造成无限循环【死循环】,我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死崩溃! 思考 1+2+3+4+…+100=?
package com. zhong. struct ;
public class whileDemo01{
public static void main ( String [ ] args) {
int i = 0 ;
while ( i< 100 ) {
i++ ;
}
System . out. printIn ( i) ;
}
}
[死循环]一直循环的代码【while(true)】
package com. zhong. struct ;
public class whileDemo02{
public static void main ( String [ ] args) {
while ( true ) {
}
}
}
计算1到100的和
package com. zhong. struct ;
public class whileDemo01{
public static void main ( String [ ] args) {
int i = 0 ;
int sum = 0
while ( i<= 100 ) {
sum = sum + i;
i++ ;
}
System . out. printIn ( sum) ;
}
}