You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

控制台数学答题程序添加单题6秒限时功能的技术实现问询

Adding a 6-Second Time Limit to Your Math Quiz Questions

Hey there! Adding a time limit to each question is a great touch for your school math quiz project—let's walk through how to implement this smoothly in Java, building on your existing code.

The core issue with your current loop is that in.nextInt() blocks the program indefinitely until the user inputs something. To fix this, we can use asynchronous input handling with Java's ExecutorService, which lets us set a timeout for the user's response.

Step-by-Step Implementation

First, you'll need to import the necessary concurrent classes at the top of your file:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.ExecutionException;

Then, modify your core loop to add the time limit logic:

// Create a single-threaded executor to handle user input asynchronously
ExecutorService inputExecutor = Executors.newSingleThreadExecutor();
int score = 0;

for (int i = 0; i < 10; i++) {
    System.out.println("\nQuestion " + (i+1) + ": " + questions[i]);
    
    // Submit a task to read the user's input
    Future<Integer> inputTask = inputExecutor.submit(() -> {
        // Use a local Scanner here to avoid blocking issues across questions
        Scanner in = new Scanner(System.in);
        return in.nextInt();
    });
    
    try {
        // Wait up to 6 seconds for the user's answer
        int userAnswer = inputTask.get(6, TimeUnit.SECONDS);
        
        // Check if the answer is correct
        if (userAnswer == answers[i]) {
            score++;
            System.out.println("✅ Correct!");
        } else {
            System.out.println("❌ Wrong answer. The correct answer was: " + answers[i]);
        }
    } catch (TimeoutException e) {
        // Triggered if the user doesn't answer in 6 seconds
        System.out.println("⏰ Time's up! You didn't answer within 6 seconds.");
        // Cancel the input task to free up the thread
        inputTask.cancel(true);
    } catch (InterruptedException | ExecutionException e) {
        // Handle cases where input is invalid (e.g., non-integer) or the task is interrupted
        System.out.println("❌ Invalid input or an error occurred.");
        e.printStackTrace();
    }
}

// Shutdown the executor once all questions are done
inputExecutor.shutdown();
System.out.println("\nQuiz complete! Your final score is: " + score + "/10");

Key Details to Note

  • Asynchronous Input: We use ExecutorService to run the input-reading logic in a separate thread, so the main thread can wait with a timeout instead of blocking indefinitely.
  • Timeout Handling: The get(6, TimeUnit.SECONDS) method throws a TimeoutException if no input is received within 6 seconds—we catch this to mark the question as unanswered.
  • Cleanup: We call inputTask.cancel(true) on timeout to stop the input thread from waiting for input, and shut down the executor when the quiz ends to free resources.
  • Input Validation: The ExecutionException will catch cases where the user enters a non-integer (since nextInt() throws an exception), so you might want to add extra logic here to handle that more gracefully if needed.

Let me know if you need help adjusting this to fit your full program, or if you run into any edge cases (like multiple inputs being entered at once)!

内容的提问来源于stack exchange,提问作者Ryan Snyder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:05:26