How can I implement a timer within a for loop in Java?

82 Views Asked by At

I've recently started learning Java and am attempting to create a multiplication game with a timer function.

Here's how the game is intended to run:

  • Players engage in five questions per a round
  • Answers must be provided within 3 seconds.
  • Correct answers earn 20 points each.

I've been working on implementing a timer using Timer and TimerTask, and it seems to work partially. However, I'm encountering an issue where the program gets stuck when the time is up and doesn't continue to the next iteration of the loop.

I appreciate your assistance in answering my initial question on Stack Overflow!

Thank you!

import java.util.Random;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class GameLogic {

    private static Timer timer;
    private static int score = 0;

    public static void playGame() {
        Scanner keyboard = new Scanner(System.in);

        // Generate five questions per a round
        int roundCount = 5;

        for (int i = 1; i <= roundCount; i++) {
            timer = new Timer();
            // Generate random numbers and multiply them
            Random random1 = new Random();
            Random random2 = new Random();
            int firstNum = random1.nextInt(9) + 1;
            int secondNum = random2.nextInt(9) + 1;
            int multiply = firstNum * secondNum;
            System.out.printf("%n%d X %d%n", firstNum, secondNum);


            // Schedule the timer task
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("Time's up");
                    timer.cancel();
                }

            }, 3000);


            int answer = keyboard.nextInt();

            if (keyboard.hasNextInt()) {
                answer = 0;
            } else {
                answer = keyboard.nextInt();
            }


            if (answer == multiply) {
                System.out.println("Correct!");
                score += 20;
            } else {
                System.out.println("Incorrect!");
            }
        }
    }
  
  public static void main(String[] args) {
    playGame();
  }
}
1

There are 1 best solutions below

2
Semaphor On

I think your problem has nothing to do with the timer itself. The following part of your code does not make sense to me:

        int answer = keyboard.nextInt();

        if (keyboard.hasNextInt()) {
            answer = 0;
        } else {
            answer = keyboard.nextInt();
        }

After you printed the question with the multiplication, the code reads an integer. But then the code waits within the if for the next input to check if its an integer but does not read it. You need to get rid of this if/else block.

Then you should cancel the timer after the user entered an input. Cancelling the timer after it already printed out that the time is up is too late. And you probably need to exit the game if the time is up.

Then you can print the score at the end. The final program may look like:

import java.util.Random;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

class GameLogic {

    private static Timer timer;
    private static int score = 0;

    public static void playGame() {
        Scanner keyboard = new Scanner(System.in);

        // Generate five questions per a round
        int roundCount = 5;

        for (int i = 1; i <= roundCount; i++) {
            timer = new Timer();
            // Generate random numbers and multiply them
            Random random1 = new Random();
            Random random2 = new Random();
            int firstNum = random1.nextInt(9) + 1;
            int secondNum = random2.nextInt(9) + 1;
            int multiply = firstNum * secondNum;
            System.out.printf("%n%d X %d%n", firstNum, secondNum);


            // Schedule the timer task
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("Time's up");
                    System.exit(1);
                }

            }, 3000);


            int answer = keyboard.nextInt();
            timer.cancel();

            if (answer == multiply) {
                System.out.println("Correct!");
                score += 20;
            } else {
                System.out.println("Incorrect!");
            }
        }
        System.out.println("Your score: " + score);
    }

    public static void main(String[] args) {
        playGame();
    }
}