java单分支例子_Java随机减法题,单分支的应用实例

/*

每次产生5个随机减法算术题,提示用户输入答案,

并判断是否正确,最后显示正确答案以及答题时间

涉及知识点:

1.随机数的生成方法Math.random()

2.条件分支语句if

3.获取时间System.currentTimeMillis(),

4.三元运算符代替if

5.String 的巧妙使用

*/

package Example;

import java.util.Scanner;

public class Minus {

public static void main(String[] args) {

// TODO Auto-generated method stub

final int numberofquestions = 5;//题目数量

int corrrectcount = 0;       //答对数量

int count = 0;               //答题计数器

long stsrttime = System.currentTimeMillis();  //获取时间

String output = "";

Scanner input = new Scanner(System.in);  //创建输入

while (count

{

int num1 = (int)(Math.random()*10);//产生随机数

int num2 = (int)(Math.random()*10);

if (num1=num2

{

int temp = num1;

num1 = num2;

num2 = temp;

}

System.out.println("What is "+num1+" - "+num2+"?\n");//输出问题

int answer = input.nextInt();  //输入

if (num1-num2 == answer)

{

System.out.print("You are corrrect!\n");

corrrectcount++;

}

else

System.out.print("You are wrong!\nThe correct answer should be "

+(num1-num2)+"\n");

count++;

//String 的巧妙使用,三元运算符代替if

output += "\n"+num1+" - "+num2+ " = " + answer + ((num1-num2==answer)?

" correct":" wrong");

}

long endtime = System.currentTimeMillis();  //获取时间

long lasttime = endtime -stsrttime;

System.out.println("Correctnumber is "+corrrectcount+"\n"

+"Test time is "+lasttime/1000 + " seconds\n" + output);

}

}

/*

运行结果:

What is 7 - 1?

5

You are wrong!

The correct answer should be 6

What is 4 - 2?

5

You are wrong!

The correct answer should be 2

What is 2 - 0?

5

You are wrong!

The correct answer should be 2

What is 2 - 1?

55

You are wrong!

The correct answer should be 1

What is 8 - 0?

5

You are wrong!

The correct answer should be 8

Correctnumber is 0

Test time is 14 seconds

7 - 1 = 5 wrong

4 - 2 = 5 wrong

2 - 0 = 5 wrong

2 - 1 = 55 wrong

8 - 0 = 5 wrong

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值