簡體   English   中英

嘗試-抓住if-else if指令

[英]Try - Catch in if - else if instruction

我能夠實現try的功能-捕獲變量選擇,效果很好。 我有可變的stopnie問題。 我想檢查一下這是否是數值。 不幸的是,我試圖將其扔到嘗試捕獲中

class Task {

public static void main(String[] args) {
    Scanner user_input = new Scanner (System.in);
    System.out.println("Pick 1 to convert Fahrenheit to Celsius");
    System.out.println("Pick 2 to convert Ceslius to Fahrenheit");
    int choice = 0;
    double stopnie = 0.0;
    double convert = 0.0;
    DecimalFormat df = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
    boolean loop = true;

while (loop) 
{
    try 
    {
        choice = user_input.nextInt();
        loop = false;
    } 
    catch (Exception e) 
    {
        System.out.println("Bad value");
        System.out.println("Try again");
        user_input.next();

    }
}

    if(choice == 1) 
    { 
        System.out.println("Let me know Celsius value");
        stopnie = user_input.nextDouble();
        convert = stopnie/1.8-35;
        System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
    }

    else if (choice == 2) 
    {
        System.out.println("Let me know Fahrenheit value");
        stopnie = user_input.nextDouble();
        convert = stopnie*1.8+35;
        System.out.println(stopnie + " F " + " = " + convert + " C");

    }

    else 
    {
        System.out.println("Bad value");
    }

}   

}

所以,我添加了try catch到if(choice == 1):with while循環

    if(choice == 1) 
    { 
        while (loop) 
        {
        try {
            System.out.println("Let me know Celsius value");
            stopnie = user_input.nextDouble();
            convert = stopnie/1.8-35;
            System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
            } catch (Exception e) {
                System.out.println("Bad value");
                System.out.println("Try again");
                user_input.next();
            }
        }
    }

現在,當我啟動程序並選擇1時,什么都沒有發生。 我想選擇1,轉到函數if(chooice == 1),如果出現任何錯誤打印錯誤值,請重試並再次添加輸入到put值

試試這個代碼:

public static void main(String[] args) {
        Scanner user_input = new Scanner (System.in);
        try {
            int f=user_input.nextInt();
            System.out.println("It's an Integer");
        } catch (InputMismatchException e) {
            System.out.println("It's not Integer");
            // Should print the exception
           //e.printStackTrace();

        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM