循环结构
while循环
do……while循环
for循环
在java5中引入了一种主要用于数组的增强性for循环
while循环
while是最基本的循环,它的结构为:
while(布尔表达式){
//循环内容
}
- 只要布尔表达式为true,循环就会一直执行下去。
- 我们大多数情况是会让循环停止下来的,我们需要一个表达式失效的方式来结束循环。
- 少部分情况需要循环一直执行,比如服务器的请求响应监听等。
- 循环条件一直为true就会造成无限死循环,我们正常的业务编程中应尽量避免死循环。会影响程序性能或者造成程序卡死崩溃!
package com.xu.struct;
public class WhileDemo01 {
public static void main(String[] args) {
int i = 0;
while (i<1000){
i++;
System.out.println(i);
}
}
}
package com.xu.struct;
public class WhileDemo02 {
public static void main(String[] args) {
//死循环 while (true){
//等待客户端链接
//定时检查
//。。。。。。
String name = "发财啦!";
while (name.equals("发财啦!")){
System.out.println(name);
}
String vb = "我叫你一声,你敢答应吗?";
while (vb==("我叫你一声,你敢答应吗?")){
System.out.println(vb);
}
}
}
package com.xu.struct;
public class WhileDemo03 {
public static void main(String[] args) {
String name = "黑客入侵!………………前方高能预警!!!010110111010$0#11010101110$$000101100100000000";
while (name.equals("黑客入侵!………………前方高能预警!!!010110111010$0#11010101110$$000101100100000000")){
System.out.println(name);
}
}
}
package com.xu.struct;
public class WhileDemo04 {
public static void main(String[] args) {
//计算1+2+3+……+100= ?
//高斯的故事
int i = 0;
int sum = 0;
while (i<=100){
sum = sum + i;
i++;
}
System.out.println(sum);
}
}
do...while循环
-
对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件也至少执行一次。
-
do…while循环和while循环相似,不同的是,do…while循环至少会执行一次。
do{
//代码语句
}while(布尔表达式);
package com.xu.struct;
public class WhileDemo05 {
public static void main(String[] args) {
int i = 0;
while (i<0){
i++;
System.out.println(i);
}do {
i++;
}while (i<0);
System.out.println(i);
}
}
For循环
- 虽然所有结构都可以用while或者do…while表示,但java提供了另外一种语句——for循环,使一些结构变得更加简单。
- for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构。
- for循环执行的次数是在执行前就确定的。语法格式如下:
for(初始化;布尔表达式;更新){
//代码语句
}
package com.xu.struct;
public class ForDemo1 {
public static void main(String[] args) {
//计算0到100之间的奇数和偶数的和
int oddSum = 0;
int evenSum = 0;
for (int i = 0; i <= 100; i++) {
if (i%2!=0){ //奇数
oddSum+=i;
}else{
evenSum+=i; //偶数
}
}
System.out.println("奇数的和: "+oddSum);
System.out.println("偶数的和:"+evenSum);
}
}
package com.xu.struct;
public class ForDemo02 {
public static void main(String[] args) {
//用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
for (int i = 1; i <= 1000; i++) {
if (i%5==0){
System.out.print(i + "\t");
}
if (i%15==0){
System.out.println();
}
}
//println 输出完会换行
} //print输出完不会换行
}
package com.xu.struct;
public class ForDemo03 {
public static void main(String[] args) {
int i = 0;
while (i<=100){
i++;
if (i%5==0){
System.out.print(i + "\t");
}
if (i%15==0){
System.out.println();
}
}
}
}
package com.xu.struct;
public class ForDemo04 {
public static void main(String[] args) {
//打印九九乘法表
for (int j = 1; j <= 9; j++) {
for (int i = 1; i <=j; i++) {
System.out.print(i+ "*" + j + "=" + (i*j) + "\t");
}
System.out.println();
}
}
}