简体   繁体   中英

Try - Catch in if - else if instruction

I was able to implement the function of the try - catch for the variable choice and it works great. I have a problem with variable stopnie. I want to check if this is numerical value. I tried to throw it in the try catch, unfortunately without success

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");
    }

}   

}

so, I added 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();
            }
        }
    }

Now, when I start program and Pick 1 nothing happens. I want to pick 1, go to function if(chooice ==1) and if there will be any error print Bad value, try again and add input to put value again

try this code:

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

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM