Java实现用户5秒未输入自动退出程序及代码完善咨询
Fixing the 5-Second Auto-Exit for Your Java Temperature Converter
Got it, let's get your countdown auto-exit logic working properly. Your current attempt with Timer is on the right track, but it's missing a few key pieces: canceling the timer when the user inputs a value, handling invalid inputs, and proper resource cleanup. Here's the complete, working version:
import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; import java.util.InputMismatchException; public class TemperatureConverter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Bonjoir lol \n Convertire de Celsius à Fahrenheit tape 1 \n Convertire de Fahrenheit à Celsius tape 2 "); // Initialize timer and countdown task Timer timer = new Timer(); TimerTask countdownTask = new TimerTask() { int remainingTime = 5; // Start with 5 seconds @Override public void run() { remainingTime--; System.out.println("Temps restant : " + remainingTime + " secondes"); if (remainingTime == 0) { System.out.println("Aucune entrée détectée. Fermeture du programme..."); timer.cancel(); System.exit(0); } } }; // Start countdown: first run after 1 second, repeat every 1 second timer.scheduleAtFixedRate(countdownTask, 1000, 1000); int choix = -1; try { // Wait for user input choix = sc.nextInt(); // Cancel timer immediately once input is received timer.cancel(); countdownTask.cancel(); // Handle temperature conversion based on user choice switch (choix) { case 1: System.out.println("Entrez la température en Celsius :"); double celsius = sc.nextDouble(); double fahrenheit = celsius * 9/5 + 32; System.out.printf("%.2f°C = %.2f°F%n", celsius, fahrenheit); break; case 2: System.out.println("Entrez la température en Fahrenheit :"); double fahr = sc.nextDouble(); double cel = (fahr - 32) * 5/9; System.out.printf("%.2f°F = %.2f°C%n", fahr, cel); break; default: System.out.println("Choix invalide. Fermeture du programme..."); break; } } catch (InputMismatchException e) { // Handle invalid input (non-integer) timer.cancel(); countdownTask.cancel(); System.out.println("Entrée invalide. Fermeture du programme..."); } finally { // Clean up scanner resource sc.close(); } } }
Key Improvements Explained
- Proper Countdown Tracking: The
remainingTimevariable is a member of theTimerTaskanonymous class, so it persists across each run of the task and correctly decrements each second. - Cancel Timer on Input: As soon as the user enters a value (valid or invalid), we cancel both the timer and the task to stop the countdown immediately—no more unexpected exits after user input.
- Input Exception Handling: We catch
InputMismatchExceptionto handle cases where the user enters something that's not an integer, with a clean exit message. - Resource Cleanup: The
Scanneris closed in afinallyblock to avoid resource leaks. - Stable Timing: Using
scheduleAtFixedRateinstead ofscheduleensures the countdown stays consistent, even if a task run is delayed slightly.
Issues in Your Original Code
- The timer wasn't being canceled after user input, so it would keep counting down and exit the program even if the user had already made a selection.
- There was no handling for invalid input (like non-integer values), which would cause an uncaught exception.
- No resource cleanup for the
Scannerobject.
内容的提问来源于stack exchange,提问作者Anas Selkane
相关产品推荐
相关产品推荐

