尚硅谷Java学习第十三篇:循环结构

1.循环结构的四要素

	① 初始化条件
	② 循环条件 ---->是boolean类型
	③ 循环体
	④ 迭代条件

说明:在通常情况下,循环结束都是因为②中循环条件返回false。

2.三种循环结构

2.1 for循环

for(①;②;④){

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

2.2 while循环结构

①
while(②){
	③;
	④;
}
执行过程:① - ② - ③ - ④ - ② - ③ - ④ - ... - ②

说明:

1. 写while循环千万小心不要丢了迭代条件④。一旦丢了,就可能导致死循环!
2. 我们写程序,要避免出现死循环;
3. for循环和while循环时可以相互转换的!

2.3 do-while循环结构

①
do{
		③;
		④;
}while(②);
执行过程:① - ③ - ④ - ② -③ - ④  - ... - ②

说明:

1. do-while循环至少会执行一次循环体!
2. 开发中,使用for和while更多一些。较少使用do-while

for循环练习 1:
编写程序从1循环到150,并在每行打印一个值,另外在每个3的倍数行上打印出"foo",在每个5的倍数行上打印"biz",在每个7的倍数行上打印输出"baz"。

class ForExer1 {
	public static void main(String[] args) {
		int i;
		for(i = 1;i <= 150;i++){
			
			System.out.print(i + "  ");
			
			if(i % 3 == 0)
				System.out.print("foo  ");
		    if(i % 5 == 0)
				System.out.print("biz  ");
			if(i % 7 == 0)
				System.out.print("baz  ");
			
			System.out.println();
		}
	}
}

for循环练习 2:

题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
eg:12和20的最大公约数是4,最小公倍数是60。

import java.util.Scanner;
class ForExer2 {
	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		
		System.out.println("请输入第一个正整数:");
		int m = scan.nextInt();
		System.out.println("请输入第二个正整数:");
		int n = scan.nextInt();
		//获取最大公约数
		// 1.获取两个数中的最小值
		int min = (m <= n)? m : n;
		// 2.从后往前遍历找出最大公约数
		for(int i = min;i >= 1 ;i--){
			if(m % i ==0 && n % i ==0){
				System.out.println("最大公约数为:" + i);
				break;//一旦在循环中执行到break,就跳出循环。
			}
		}
		//获取最大公约数
		// 1.获取两个数中的最大值
		int max = (m > n)? m : n;
		// 2.从前往后遍历找出最小公倍数
		for(int i = max;i < m * n;i++){

			if(i % m == 0 && i % n == 0){
				System.out.println("最小公倍数为:" + i);
				break;//一旦在循环中执行到break,就跳出循环。
			}
		}

	}
}

while循环练习 1:
题目:
从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。

说明:

1. 不在循环条件部分限制次数的结构:for(;;)或while(true)
2. 结束循环有几种方式?
	方式一:循环条件部分返回false
	方式二:在循环体中,执行break
import java.util.Scanner;

class XunHuanExer1 {
	public static void main(String[] args) 	{

		Scanner scan = new Scanner(System.in);
		//int num = scan.nextInt();
		int positiveNum = 0;//记录正数的个数
		int negativeNum = 0;//记录负数的个数
		/*
		while(num != 0){
			if(num > 0){
				positiveNum ++;
			}
			else
				negativeNum ++;
			num = scan.nextInt();
		}
		*/
		while(true){
			int num = scan.nextInt();
			if(num > 0){
				positiveNum ++;
			}
			else if(num < 0){
				negativeNum ++;
			}
			else{
				break;//一旦执行break,跳出循环。
			}
		}


		System.out.println("正数的个数为:" + positiveNum);
		System.out.println("负数的个数为:" + negativeNum);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值