码迷,mamicode.com
首页 > 编程语言 > 详细

Java随机减法题,单分支的应用实例

时间:2021-02-25 11:58:49      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ring   main   +=   while   ==   oid   int   next   NPU   

/*
每次产生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<numberofquestions)
        {
            int num1 = (int)(Math.random()*10);//产生随机数
            int num2 = (int)(Math.random()*10);
            if (num1<num2)                     //使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

 

*/

 

Java随机减法题,单分支的应用实例

标签:ring   main   +=   while   ==   oid   int   next   NPU   

原文地址:https://www.cnblogs.com/Alic5/p/14443326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!