循环结构练习题(一)

1、求100以内的所有素数

public static void main(String[] args) {
	int i, j;

	for (i = 2; i <= 100; i++) {
		for (j = 2; j < i; j++) {
			if (i % j == 0)
					break;
		}
		if (j >= i) {// 也可以写成j==i
			System.out.print(i + " ");
		}
	}

}

2、随机产生一个1-100之间的整数,看能几次猜中。要求:猜的次数不能超过7次,每次猜完之后都要提示“大了”或者“小了”。

    public static void main(String[] args) {
		// 创建键盘录入对象
		Scanner sc = new Scanner(System.in);

		// 随机产生一个1-100之间的整数
		int num = (int) (Math.random() * 100 + 1);
		System.out.println(num);

		// 设置猜测的次数
		int count = 1;

		while (count <= 7) {
			System.out.println("请输入你猜测的数字:");
			int guess = sc.nextInt();
			if (guess > num) {
				System.out.println("大了");
				count++;
			} else if (guess < num) {
				System.out.println("小了");
				count++;
			} else {
				System.out.println("猜对了");
				break;
			}

		}

		if (count > 7) {
			System.out.println("只能猜测7次,机会用完了");
		} else {
			System.out.println("猜了" + count + "次");
		}

		sc.close();

	}

3、输出小写的a-z以及大写的在Z—A

        A:65    Z:90   a:97   z:122

    public static void main(String[] args) {
		for (int i = 97; i <= 122; i++) {
			char ch = (char) i;
			System.out.print(ch + " ");
		}

		System.out.println();

		for (int i = 65; i <= 90; i++) {
			char ch = (char) i;
			System.out.print(ch + " ");
		}

	}

4、输出20-80之间能被3整除的整数,每5个一行

    public static void main(String[] args) {
		int num = 20;
		int count = 0;
		while (num <= 80) {
			if (num % 3 == 0) {
				System.out.print(num + " ");
				count++;

				if (count % 5 == 0) {
					System.out.println();
				}
			}

			num++;
		}

	}

5、打印出1000-2000年中所有的闰年,并以每行四个数的形式输出

    public static void main(String[] args) {
		int year = 1000;
		int count = 0;
		while (year <= 2000) {
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
				System.out.print(year + " ");
				count++;
				
				if (count % 4 == 0) {
					System.out.println();
				}
			}

			year++;
		}

	}

6、A、B、C、D分别为0——9之间的整数,求出满足AB+CD=DA条件的数。

    例如:90+09=99

    public static void main(String[] args) {
		for (int a = 0; a < 10; a++) {
			for (int b = 0; b < 10; b++) {
				for (int c = 0; c < 10; c++) {
					for (int d = 0; d < 10; d++) {
						if (10 * a + b + 10 * c + d == 10 * d + a) {
							System.out.println(a + "" + b + "+" + c + "" + d + "=" + d + a);
						}
					}
				}
			}
		}
	}

7、输出九九乘法表

    public static void main(String[] args) {
		// 外层循环控制行数
		for (int i = 1; i <= 9; i++) {
			// 内层循环控制列数
			for (int j = 1; j <= i; j++) {
				System.out.print(j + "*" + i + "=" + (i * j) + "\t");
			}

			System.out.println();
		}

	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值