使用for循环运行试验,同时收集响应时间和正确答案?

时间:2017-04-05 03:19:11

标签: java jgrasp

处理一个项目,该项目要求我包含一个for循环来运行由变量NUM_TRIALS指定的多个试验。 for循环还负责收集用户给出的响应时间和正确答案的数量。任何帮助将不胜感激。

import java.util.Scanner;
import java.util.Random;

public class ResponseTimeExperimentProject
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      Random rand = new Random();


      System.out.print("Please enter your name: ");
      String name = in.nextLine();

      System.out.println("Hello " + name 
         + ". Please answer as fast as you can."
         + "\n\nHit <ENTER> when ready for the question.");

      in.nextLine();  // wait for user to hit <ENTER>

      int NUM_TRIALS = 4;


      int a =(rand.nextInt(65536)-32768);
      int b =(rand.nextInt(65536)-32768);

      long startTime = System.currentTimeMillis();

      System.out.print(a + " - " + b + " = ");
      String response = in.nextLine();
      int number = Integer.parseInt(response);

      long endTime = System.currentTimeMillis();


      int outcome = number == a - b ? 1 : 0;


      long reactionTime = endTime - startTime;

      System.out.println(outcome == 1? "Correct!" : "Incorrect."); 

      System.out.println("Thank you "  + name + ", goodbye.");
   }
}

1 个答案:

答案 0 :(得分:0)

这是你想要的东西吗?我所做的只是在for循环中包装你所做的,然后更改几个变量,以便它们可以在for循环之外使用。

import java.util.Scanner;
import java.util.Random;

public class ResponseTimeExperimentProject
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        Random rand = new Random();


        System.out.print("Please enter your name: ");
        String name = in.nextLine();

        System.out.println("Hello " + name
                + ". Please answer as fast as you can."
                + "\n\nHit <ENTER> when ready for the question.");

        in.nextLine();  // wait for user to hit <ENTER>

        int NUM_TRIALS = 4;

        int totalTime = 0;
        int numCorrect = 0;

        for(int i = 0; i < NUM_TRIALS; i++) {
            int a = (rand.nextInt(65536) - 32768);
            int b = (rand.nextInt(65536) - 32768);

            long startTime = System.currentTimeMillis();

            System.out.print(a + " - " + b + " = ");
            String response = in.nextLine();
            int number = Integer.parseInt(response);

            long endTime = System.currentTimeMillis();

            boolean correct = number == a - b ? true : false;
            if(correct){
                System.out.println("Correct!");
                numCorrect++;
            }else{
                System.out.println("Incorrect!");
            }

            totalTime += endTime - startTime;
        }

        System.out.println(String.format("You got %s answers correct out of %d",numCorrect, NUM_TRIALS));
        System.out.println(String.format("Your average response time was %d milliseconds",totalTime / NUM_TRIALS));

        System.out.println("Thank you "  + name + ", goodbye.");
    }
}