"无限"循环
语法格式:
- 最简单“无限”循环格式:
while(true)
、for(;;)
适用场景:
- 开发中,有时并不确定需要循环多少次,需要根据循环体内部某些条件,来控制循环的结束(使用break)
- 如果此循环结构不能终止,则构成了死循环!开发中要避免出现死循环。
**案例1:**实现爱你到永远…
public class EndlessFor1{
public static void main(String[] args){
while(true){
System.out.println("I LOVE YOU!");
}
/*
for(;;){
System.out.println("I LOVE YOU!");
}
*/
//死循环后面不能有执行语句
//System.out.println("end");//永远无法到达的语句,编译报错
}
}
public class EndlessFor2 {
public static void main(String[] args) {
for (; true;){ //条件永远成立,死循环
System.out.println("我爱你!");
}
}
}
public class EndlessFor3 {
public static void main(String[] args) {
for (int i=1; i<=10; ){ //循环变量没有修改,条件永远成立,死循环
System.out.println("我爱你!");
}
}
}
思考:如下代码执行效果
public class EndlessFor4 {
public static void main(String[] args) {
for (int i=1; i>=10; ){ //一次都不执行
System.out.println("我爱你!");
}
}
}
**案例2:**从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。
import java.util.Scanner;
class ForWhileTest1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int PostiveCount = 0;
int NegitiveCount = 0;
while(true){
System.out.print("请输入一个整数(输入为0时结束程序):");
int num = scan.nextInt();
if(num > 0){
PostiveCount++;
}else if(num < 0){
NegitiveCount++;
}else{
System.out.printl("程序结束");
break;
}
}
scan.close();
System.out.println("读入"+PostiveCount+"个正数,读入"+NegitiveCount+"个负数");
}
}