繁体   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