java while 循环练习题

这篇博客包含两个Java程序,分别用于计算一个数的阶乘和打印1到100之间的所有奇数。第一个程序使用while循环和递归计算阶乘,当输入为负数时会提示错误。第二个程序通过while循环遍历1到100,打印出所有奇数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、求一个数的阶乘

代码:

import java.util.Scanner;

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

//	         
//		// 求阶乘
	
		Scanner sc = new Scanner(System.in);
	
		while (true) {
			int res = 1;
			int num = sc.nextInt();
			int n = num;
			
			if (n<=0) {
				System.out.println("整数输入不能为负数!");
				
			} else {
				while (n >= 1) {
					res = res * n;
					n = n-1;
					
							
					
				}
				System.out.println(num+"的阶乘是:"+res);
				
			}
			
			
		}
		
		
		
	}

}

二、求1-100 之间的奇数

代码:

public class While01 {
	public static void main(String[] args) {
		// 求1-100 之间的奇数
		int count = 0;
		
		while(count <100) {
			if (count%2 != 0) {
				System.out.println(count);
				
			}
			count++;// count 每次自增1 相当于count = count +1;
		}
		
	}
		

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值