java中For循环结构的使用

/*
For循环结构的使用
一、循环结构的4个要素
① 初始化条件
② 循环条件 —>是boolean类型
③ 循环体
④ 迭代条件

二、for循环的结构

for(①;②;④){

}

执行过程:① - ② - ③ - ④ - ② - ③ - ④ - … - ②

*/
class ForTest {
public static void 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!");
	*/

	for(int i = 1;i <= 5;i++){//i:1,2,3,4,5
		System.out.println("Hello World!");
	}
	//i:在for循环内有效。出了for循环就失效了。
	//System.out.println(i);
	
	//练习:
	int num = 1;
	for(System.out.print('a');num <= 3;System.out.print('c'),num++){
		System.out.print('b');
	}
	//输出结果:abcbcbc

	System.out.println();

	//例题:遍历100以内的偶数,输出所有偶数的和,输出偶数的个数
	int sum = 0;//记录所有偶数的和
	int count = 0;//记录偶数的个数
	for(int i = 1;i <= 100;i++){
		
		if(i % 2 == 0){
			System.out.println(i);
			sum += i;
			count++;
		}
		//System.out.println("总和为:" + sum);
	}

	System.out.println("总和为:" + sum);
	System.out.println("个数为:" + count);

}

}


/*
编写程序从1循环到150,并在每行打印一个值,
另外在每个3的倍数行上打印出“foo”,
在每个5的倍数行上打印“biz”,
在每个7的倍数行上打印输出“baz”。

*/

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

	for(int 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();

	}

}

}


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

说明:break关键字的使用:一旦在循环中执行到break,就跳出循环

*/

import java.util.Scanner;
class ForTest{

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;
		
		}
	}
	
}

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值