尝试 - 抓住if - else if指令

时间:2015-05-31 12:46:19

标签: java if-statement try-catch

我能够为变量选择实现try-catch的功能,并且效果很好。我有变量stopnie的问题。我想检查这是否是数值。我试图将它扔进try catch,遗憾的是没有成功

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 to if(choice == 1):with while loop

    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)并且如果有任何错误打印Bad值,再试一次并添加输入再次放置值

1 个答案:

答案 0 :(得分:0)

试试这段代码:

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();

        }

    }