Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
                    }
                }
            }
    
            System.out.println("Your nett income is " + nett);
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading