控制台数学答题程序添加单题6秒限时功能的技术实现问询
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
ExecutorServiceto 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 aTimeoutExceptionif 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
ExecutionExceptionwill catch cases where the user enters a non-integer (sincenextInt()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

