java的循环结构

for循环结构

1.格式:
①初始化条件
②循环条件
③迭代条件
④循环体
for(①;②;③){
 

}

2.执行过程:①-②-④-③-②-④-③

public class ForXunhuan {
	public static void main(String[] args){
				
		for(int i = 0;i < 4;i++){
			System.out.println("hello world!");
		}	
		System.out.println("------------------");
		
		int j = 1;
		for(System.out.print("a");j < 4;System.out.print("b"),j++){
			System.out.print("c");
		}
		
		System.out.println("题目:输出100以内的所有偶数及所有偶数的和及偶数的个数");
		int sum = 0;
		int count =0;
		for(int k = 0;k < 100;k++){
			if (k % 2 == 0){
				System.out.print(k);
				sum += k;
				count += 1;
			}
		}
		
		System.out.println("\n偶数和:" + sum);
		System.out.println("偶数的个数"+count);

while循环结构:

while
①初始化条件
②循环条件
③迭代条件
④循环体
 1.格式:
 ①
 while(②){
 
 
 }
 2.执行过程:①-②-④-③-②-④-③

 for循环与while循环一定可以转换。

public class WhileXunhuan {
	public static void main(String[] args){
		System.out.print("100以内的偶数和:");
		int i = 0;
		int sum = 0;
		while(i < 100){
			if(i % 2 ==0){
				sum += i;
			}
			i++;
		}
		System.out.println(sum);
	}
}

do-while循环结构

①初始化条件
②循环条件
③迭代条件
④循环体

do{


}while(②);

do-while和while的区别:do-while 至少执行一次。

public class DoWhileXunhuan {
	public static void main(String[] args){
		int i = 1;
		int sum = 0;
		do{
			if(i % 2 ==0){
				sum += i;				
			}
			i++;
		}while(i <= 100);
		System.out.println(sum);
		
		int j = 10;
		do{
			System.out.println(j);
			j++;
		}while(j < 10);
		
		while(j < 10){
			System.out.println(j);
			j++;
		}
	}
}
/*
 * 从键盘读入个数为10个的整数,并判断读入的正数和负数的个数,输入0结束。
 * 从键盘读入个数为不确定的整数,并判断读入的正数和负数的个数,输入0结束。
 * 无限循环:for(){;;}或者while(true){}
 * 说明:一般情况下,在无限循环内部要有程序终止的语句,使用break实现。若没有,那就是死循环了。
 */
import java.util.Scanner;
public class LianxiXunhuan {
	public static void main(String[] args){
		Scanner s = new Scanner(System.in);
		int a = 0;
		int b = 0;
		/*
		for(int i = 1;i <= 10;i++){
			int num = s.nextInt();
			if(num > 0){
				a += 1;
			}
			else if(num < 0){
				b += 1;
			}
			else{
				break;
			}
		}
		*/
//		for(;;)
		while(true)
		{
			int num = s.nextInt();
			if(num > 0){
				a += 1;
			}
			else if(num < 0){
				b += 1;
			}
			else{
				break;
			}	
		}
		
		System.out.println("正数的个数:" +a);
		System.out.println("负数的个数:" +b);
	}
}

break语句

1.break语句用于终止某个语句块的执行。

2.break语句出现在多层嵌套的语句块中时,可以通过标签指明要终止的是哪一层语句块 。

continue语句

1.continue语句用于跳过某个循环语句块的一次执行 。

2.continue语句出现在多层嵌套的循环语句体中时,可以通过标签指明要跳过的是哪一层循环。

return:并非专门用于结束循环的,它的功能是结束一个方法。当一个方法执行到一个return语句时,这个方法将被结束。

猜你喜欢

转载自blog.csdn.net/qq_26910845/article/details/80297081