首先我们先假想需要打印一行字符串"hello gzitcast",打印100次
那么我们最笨的办法就是将该语句打印100遍System.out.println("hellogzitcast");
那么如何解决这种问题呢?
Java提供个一个称之为循环的结构,用来控制一个操作的重复执行。
public static void main(String[] args) {
int count = 0;
while (count < 100) {
System.out.println("helloWord");
count++;
}
System.out.println("over");
变量count初始化值为0,循环检查count<100 是否为true,如果为true执行循环体(while后{}之间的语句),输出"hello Word"语句,然后count自增一,重复循环,直到count是100时,也就是count<100为false时,循环停止。执行循环之后的下一条语句。
Java提供了三种类型的循环语句:while循环,do-while循环和for循环。
while语句格式:
while(条件表达式)
{
执行语句;
}
例: 想要打印5次hello world
publicstaticvoid main(String[] args) { System.out.println("hello world"); System.out.println("hello world"); System.out.println("hello world"); System.out.println("hello world"); System.out.println("hello world"); } |
2、
publicstaticvoid main(String[] args) { int x = 0; while (x < 5) { System.out.println("hello java "); } } |
如果是在dos里编译和运行,是不会停止,除非系统死机。需要ctrl+c来结束。
这就是真循环或者死循环。因为x<5 永远为真。
publicstaticvoid main(String[] args) { int x = 0; while (x < 5) { System.out.println("hello java "); x++; } } |
让x自增,那么就会有不满足条件的时候。循环就会结束。
练习:想要打印出1-100之间的奇数
publicstaticvoid main(String[] args) { int x = 1; while (x < 100) { System.out.println(x); x = x + 2; } } |
public static void main(String[] args){ int x=1; while(x<100){
if(x%2!=0){ System.out.print(x); } x++; } System.out.println(); } |
例2:计算1+2+3+4+5+6+7+8+9 的值
int sum = 0; int i = 1; while (i < 10) { sum = sum + i; i++; } System.out.println(sum); |
注意:要精确控制循环的次数。常犯错误是是循环多执行一次或者少执行一次。
例如会执行101次,想要执行100次,要么是count初始值为1,然后count<=100
要么是count初始值为0,coung<100
int count = 0; while (count <=100) { System.out.println("hello gzitcast"); count++; } System.out.println("over"); |