Java语法基础部分综合案例练习

本文介绍了多个Java编程基础案例,包括水仙花数、猜数字游戏、加法出题程序、数列求和等,涵盖了算法设计和基础操作。通过这些案例,读者可以加深对Java语言的理解和应用。
摘要由CSDN通过智能技术生成

案例1:水仙花

需求:求取所有的“水仙花数”,统计水仙花数个数,并将数字打印到控制台。
tips:

1.水仙花数是一个三位数

2.水仙花数的个位,十位,百位的数字立方和等于原数

public static void main(String[] args) {
   
		for(int i=100;i<1000;i++) {
   
			//获取个位数
			int g = i%10;
			//获取十位数
			int s = i/10%10;
			//获取百位数
			int b = i/100;
			
			if(Math.pow(g, 3)+Math.pow(s, 3)+Math.pow(b, 3)==i) {
   
				//输出水仙花数
				System.out.println(i);
			}
		}
	}

案例2:猜数字游戏

需求:系统随机生成一个0~100之间的随机数,让玩家猜,并提示大了还是猜小了,
直到猜对为止。
public static void main(String[] args) {
   
		long time = System.currentTimeMillis();
		long number = time%101;
		System.out.println(number);
		Scanner scan = new Scanner(System.in);
		System.out.println("开始猜吧。。。");
		int count = 0;
		int answer;
		do{
   
			count++;
			answer = scan.nextInt();
			if(answer > number) {
   
				System.out.println("猜大了");
			}else if(answer < number){
   
				System.out.println("猜小了");
			}else {
   
				System.out.println("猜对了");
				System.out.println("猜了"+count+"次!");
				break;//跳出循环
			}	
		}while(answer!=number);
		scan.close();
	}

案例3:随机加法出题程序

需求:系统随机出10道两位正整数以内的加法题目,让用户作答;
答对一题得10分,答错得分不扣分,满分100分;
答错的题目要提示正确答案,所有题目答题完毕后统计得分和答题时长
public static void main(String[] args) {
   

		Scanner scan = new Scanner(System.in);
		System.out.println("开始答题:");
		Random rand = new Random();
		int score = 0;
		//开始计时
		long start = System.currentTimeMillis();
		for(int i=1;i<=10;i++) {
   
			int n1 = rand.nextInt(101);
			int n2 = rand.nextInt(101);
			System.out
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值