循环结构介绍:

一、循环结构

1、while循环

语法:

while(循环条件){
循环操作
}

2. do-while循环结构

语法:

do{
循环操作
}while(循环条件);

3. for循环

语法:

for(表达式1;表达式2;表达式3){
//循环体
}
1.表达式1就是一个赋值的语句,循环结构的初始化部分,为循环变量赋初始值 例如:int i=0;
2.表达式2条件语句,循环结构的循环条件,例如:i<100
3.表达式3赋值语句,通常使用++或–运算符。循环结构的迭代部分,通常用来修改循环变量的值 例如:i++

二: 循环结构练习题

1. 从键盘分别输入年月日,使用for+if实现判断这一天是当年的第几天.

class Days{

public static void main(String[] args ){
	//从键盘输入年月日
	java.util.Scanner input = new java.util.Scanner(System.in);
	System.out.println("请输入你要查询的年份: ");
	int year = input.nextInt();
	System.out.println("请输入你要查询的月份:");
	int mouth = input.nextInt();
	System.out.println("请输入你要查询日: ");
	int day = input.nextInt();
	// 定义days累加了第mouth月的day 天
	int days = day;
	forint i=1; i<mouth; i++{
		if(i ==4 || i ==6 || i ==9 || i ==11){
			days+=30;
		}else if(i == 2){
			if(year%4==0 && year%100 == 0 || year %400 ==0{
			days+=29;
			}else{days+=28;
			}

		}else{
		days += 31;
		}
}
	System.out.println(year + "年" + month + "月" + day + "日是这一年的第" + days + "天");
	
}
}

2. java猜数字游戏(数据范围在1-100之间)

class GuessNum{
	public static void main(String[] args){
	
		java.util.Scanner sc = new java.util.Scanner(System.in);
		System.out.println("请输入你猜测的数字");
		//生成随机数
		int guessNum = (int) (Math.random()*100 + 1);
		while(true){
			int result = sc.nextInt();
			if ( result < guessNum){
				System.out.println("你猜测的数字小了");
				
			}else if(result > guessNum){
				System.out.println("你猜测的数字大了");
			}else{
				System.out.println("恭喜猜对了");
				System.out.println("继续玩请输入Y,否则输入N");
				String input = sc.next();
				if(input.equals("N")){
					System.out.println("欢迎下次再来");
					break;
				//equals() 方法比较字符串是否相等
				}else if(input.equals("Y")){
					System.out.println("正在为你接入新一轮游戏");
					System.out.println("请输入你要猜测的数字");
				}else{
					System.out.println("你的输入有误,游戏正在退出");
					break;
				}
			
			}	
		
		}
	}

}

3. 使用循环对计算从1加到100的和

方案一: while方案
public class Sum_while{
	public static void main(String[] args){
	
		int sum = 0;
		int i = 1;
		while(i<=100){
			sum += i;
			i++;
		
		}
		System.out.println("100内的整数的和是" +sum);
	
	}

}
方案二: do -while 循环
public class Sum_while{
	public static void main(String[] args){
	
		int sum = 0;
		int i = 1;
		do{
			sum += i;
			i++;
		
		}while(i <=100);
		System.out.println("100内的整数的和是" +sum);
	
	}

}
方案三 for循环
public class Sum_for{
	public static void main(String[] args){
	
		int sum = 0;
		
		for(int i =1; i<=100;i++){
			
			sum+=i;
			
		}
		System.out.println("100以内的整数和是" +sum);
	
	}

}