求助:如何实现带输入判断的Java函数?现有代码待完善
Solution for Your Java Input Handling Function
Hey Leonardo! Let's get that Java function working exactly how you need it. The main trick here is handling user input while running your countdown timer, then branching to Operation A or B based on whether input was provided.
Here's a complete, working implementation that builds on your existing code:
import java.util.Scanner; public class InputActionHandler { public static void main(String[] args) { System.out.println("Enter any key to get data or leave empty"); Scanner scanner = new Scanner(System.in); boolean inputReceived = false; String userInput = ""; try { // Start a separate thread for the countdown Thread countdownThread = new Thread(() -> { try { for (int i = 5; i > 0; i--) { if (inputReceived) { break; // Exit countdown early if input is detected } System.out.println("Starting in " + i); Thread.sleep(1000); } } catch (InterruptedException e) { // Thread gets interrupted when input is received Thread.currentThread().interrupt(); } }); countdownThread.start(); // Check for input over the 5-second window long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < 5000) { if (scanner.hasNextLine()) { userInput = scanner.nextLine().trim(); inputReceived = true; countdownThread.interrupt(); // Stop the countdown immediately break; } Thread.sleep(100); // Avoid busy waiting with a short pause } // Execute the appropriate operation if (inputReceived && !userInput.isEmpty()) { // Replace with your actual Operation A logic System.out.println("Executing Operation A..."); // Example: int value = Integer.parseInt(userInput); // If you need numeric input } else { // Replace with your actual Operation B logic System.out.println("Executing Operation B..."); } } catch (InterruptedException e) { e.printStackTrace(); } finally { scanner.close(); // Clean up the scanner resource } } }
Key Details Explained:
- Input Handling: Instead of blocking indefinitely for input, we check every 100ms over 5 seconds. This lets the countdown run while waiting for user input.
- Countdown Thread: The countdown runs in its own thread so it doesn't block the input checking. If the user enters input early, we stop the countdown right away.
- Operation Logic:
- If the user enters any non-empty text, we trigger Operation A
- If no input is entered (either the user pressed enter without typing, or the 5 seconds elapsed), we trigger Operation B
You can swap out the print statements with your actual code for Operation A and B. If you need to handle numeric input (like your original int value variable), you can parse the userInput string inside Operation A.
内容的提问来源于stack exchange,提问作者Leonardo
相关产品推荐
相关产品推荐

