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

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 remainingTime variable is a member of the TimerTask anonymous 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 InputMismatchException to handle cases where the user enters something that's not an integer, with a clean exit message.
  • Resource Cleanup: The Scanner is closed in a finally block to avoid resource leaks.
  • Stable Timing: Using scheduleAtFixedRate instead of schedule ensures 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 Scanner object.

内容的提问来源于stack exchange,提问作者Anas Selkane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:01:34