案例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