编写Java程序,显示五个加减法测验的正确率和用时

来源:互联网 发布:linux 宕机日志 编辑:程序博客网 时间:2024/06/12 14:48

代码如下:

package com.nfsbbs.test;import java.util.Scanner;public class MathsTest {public static void main(String[] args) {        Scanner sc = new Scanner(System.in);                final int MAX = 20;         final int MUST_SOLVE = 5;        int a, b;        double crt = 0;        double rate;                double startTime, endTime;        double sec;        System.out.println("Maths Test\n");        System.out.println("You need to correctly solve addition problems as quickly as you can. ");        System.out.println("You must answer " + MUST_SOLVE + " correctly before the test will end. ");        System.out.println("The operand values will be between 1 and " + MAX + ". \n");        System.out.println("Press ENTER to start the test. ");                sc.nextLine();        startTime = System.currentTimeMillis();                for(int solve = 1; solve <= MUST_SOLVE; solve++) {        a = (int) (Math.random() * MAX + 1);        b = (int) (Math.random() * MAX + 1);        System.out.println("\nWhat is " + a + " + " + b + "? ");                if(sc.nextInt() == (a + b)) {        System.out.println("CORRECT! ");        crt++;        } else {        System.out.println("WRONG! ");        }        }                rate =crt / MUST_SOLVE * 100;                endTime = System.currentTimeMillis();        sec = (endTime - startTime) / 1000;        System.out.println("\n\nYour rating is " + rate + "%. \nAnd you took " + sec + " sceonds. ");        System.out.println("\nSee you next time. ");}}

输出:

Maths TestYou need to correctly solve addition problems as quickly as you can. You must answer 5 correctly before the test will end. The operand values will be between 1 and 20. Press ENTER to start the test. What is 6 + 6? 12CORRECT! What is 4 + 20? 24CORRECT! What is 5 + 9? 14CORRECT! What is 10 + 4? 14CORRECT! What is 2 + 13? 21WRONG! Your rating is 80.0%. And you took 10.419 sceonds. See you next time.