Question

Hi I am currently doing a piece of work for coursework. So I have done this code. However how can I stop it from returning number when x number is < 0?

public class Factorial {

    public Factorial() {
        System.out.print(new C1().computeFac(10));
    }      

    /** First addicional class **/
    private class C1 {

        /** Fields **/
        private int a,result = 1;

        /** Method **/
        public int computeFac(int input) {

            if (input < 0) {
                System.out.print(new C2().printError(0));
            } else {

                for ( a = 1 ; a <= input ; a++ )

                    result = result*a;
                return (result);
            } 
            return (result);            
        }
    }

    /** Second Addicional class **/
    private class C2 {

        /** Fields **/
        String errosArray[] = {"Negative numbers are not aceptable! \nPlease try again!\n"};

        public String printError(int a) {
            return errosArray[a];
        }

    }

    /** Main Method **/
    public static void main(String [ ] args) {
        Factorial factorial = new Factorial();
    }

}
Was it helpful?

Solution

The normal approach would be to throw an exception at this point. So your code would look like:

        public int computeFac(int input) {
            if (input < 0) {
                throw new IllegalArgumentException("Negative numbers are not allowed");
            }
            for ( a = 1 ; a <= input ; a++ ) {
                result = result*a;
            }
            return result;
        }

Also, note, that it's a good idea to always use braces for loops and conditionals, even if they only have one line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top