Home > database >  How to start the calculation again after it catches an exception java
How to start the calculation again after it catches an exception java

Time:07-11

I am new to java, I'm trying to calculate the net income, I want the user to return to calculation if I get the negative net value. I tried to use try catch statement but it failing to return to where it started. Please help.

Here is my code below

public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your income: ");
        double income = scanner.nextDouble();

        System.out.print("Enter your expenses: ");
        double expenses = scanner.nextDouble();
        double nett = income - expenses;

        if (nett < 0) {

            try {
                System.out.println("Please enter correct expense value");

            } catch (Exception e) {

            }

        }

        System.out.println("Your nett income is "   nett);
    }
}

CodePudding user response:

Hm, try-catch blocks don't work that way, instead you would want to wrap your program in a while-loop:

    public class Main {
        public static void main(String[] args) {
            
            double nett = -1;

            try (Scanner scanner = new Scanner(System.in)) {
    
                while (nett < 0) {

                    System.out.print("Enter your income: ");
                    double income = scanner.nextDouble();

                    System.out.print("Enter your expenses: ");
                    double expenses = scanner.nextDouble();
                    nett = income - expenses;

                    if (nett < 0) {
                        System.out.println("Please enter correct expense value");

                    }
                }
    
            } catch (Exception e) {
                System.out.println(e.toString);
            }
    
            System.out.println("Your nett income is "   nett);
        }
    }

I also encapsulated your Scanner in a try-resources block so that it will close automatically no matter what happens.

CodePudding user response:

use do while instead of exception like this :

do { 
            System.out.print("Enter your expenses: ");
            expenses = scanner.nextDouble();
            nett = income - expenses;
        } while (nett<0);
  • Related