java学习之路 之 基本语法-程序流程控制-循环结构-while循环练习题

本文通过多个实例详细介绍了Java中while循环的应用,包括计算数列之和、打印指定大小的矩形以及阶乘等典型问题的解决方法。
public class LoopTest {
	
	public static void main(String[] args) {
		// 循环通常由四个部分组成 
		// 1) 初始化语句
		// 2) 条件判断语句
		// 3) 循环体
		// 4) 迭代语句(使循环趋于结束)
		
		/*
		while (boolean表达式) {
			循环体;
		}*/
		int result = 0;
		int i = 0; // 初始化语句
		while (i < 10) { // 条件判断语句, 循环次数=小于号后面的数-i的初始值
			result += i; // 循环体
			i++; // 迭代语句 
		}
		System.out.println("result:" + result);//打印0-9的和
		System.out.println("i:" + i);//打印while语句执行的次数
	}
}

class LoopTest2 {
	//打印1-(n-1)之间的数的总和、while语句的执行次数
	public static void main(String[] args) {
		int n = Integer.parseInt(args[0]);
		int result = 0;
		int i = 0; // 初始化语句
		while (i < n) { // 条件判断语句, 循环次数=n
			result += i; // 循环体
			i++; // 迭代语句 
		}
		System.out.println("result:" + result);
		System.out.println("i:" + i);
		
		
	}
}

class Exer5 {
	// 打印一个20*8的矩形 ********

	public static void main(String[] args) {
				int i = 0;
		while (i < 20) {
			System.out.println("********");
			i++;
		}
	}
}
class Exer6 {
	// 打印一个N*8的矩形 
	public static void main(String[] args) {
		int n = Integer.parseInt(args[0]);
				int i = 0;
		while (i < n) {
			System.out.println("********");
			i++;
		}
	}
}

class Exer7 {
	//打印100+200+300+....+1000的和
	public static void main(String[] args) {
		int result = 0;
		int i = 0; //循环因子
		while (i < =10) { 
			result += (i + 1) * 100; 
			i++; 
		}
		System.out.println("result:" + result);
	}
}

class Exer8 {
	//打印100+200+300+....+1000的和
	public static void main(String[] args) {
		int result = 0;
		int i = 100;
		while (i <= 1000) { 
			result += i; 
			i += 100; 
		}
		System.out.println("result:" + result);
	}
}

class Exer9 {
	// 求n!  n*(n-1)*(n-2).......*1
	public static void main(String[] args) {
		
		int n = Integer.parseInt(args[0]);
		int result = 1;
		int i = 1;
		while (i <= n) { 
			result *= i; 
			i++; 
		}
		System.out.println(n + "!:" + result);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值