java练习1

题目:使用for、do_while、while 3种循环语句分别实现输出1到40之间且是4的倍数的数,要求一行显示5个数据

自己写的:

public class Chp2_13{
	public static void main(String[] args){
		int i,j=1;
		System.out.println("for循环");
		//for循环
		for(i=1;i<=50;i++){
			if(i%4==0 && j!=5){
				System.out.printf("%2d ",i);
				j++;
			}
			else if(i%4==0 && j==5){
				System.out.printf("%2d \n",i);
				j=1;
			}
		}
		//dowhile
		System.out.println();
		i=j=1;
		System.out.println("dowhile循环");
		do{
			if(i%4==0 && j!=5){
				System.out.printf("%2d ",i);
				j++;
			}
			else if(i%4==0 && j==5){
				System.out.printf("%2d \n",i);
				j=1;
			}
			i++;
		}while(i<=50);
		//while	
		System.out.println();
		i=j=1;
		System.out.println("while循环");
		while(i<=50){
			if(i%4==0 && j!=5){
				System.out.printf("%2d ",i);
				j++;
			}
			else if(i%4==0 && j==5){
				System.out.printf("%2d \n",i);
				j=1;
			}
			i++;
		}
	}
}

运行结果:

for循环
 4  8 12 16 20
24 28 32 36 40
44 48
dowhile循环
 4  8 12 16 20
24 28 32 36 40
44 48
while循环
 4  8 12 16 20
24 28 32 36 40
44 48

deepseek:

public class MultiplesOfFour {
    public static void main(String[] args) {
        int count = 0; // 计数器,用于控制每行输出的个数
        
        for (int i = 1; i <= 50; i++) {
            if (i % 4 == 0) { // 判断是否是4的倍数
                System.out.print(i + "\t"); // 输出数字,用制表符分隔
                count++;
                
                if (count % 5 == 0) { // 每输出5个数字换行
                    System.out.println();
                }
            }
        }
    }
}

运行结果:

4       8       12      16      20
24      28      32      36      40
44      48

tips:制表符\n,5个一组count%5==0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值