0

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(); } } 
2
  • You can't stop it from returning a number, the method returns an int. Commented Feb 11, 2014 at 14:18
  • Yeah that's what I fort. It would have to be void. Never mind I will just keep it like that. Commented Feb 11, 2014 at 14:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the useful information, thanks a lot throw new IllegalArgumentException(new C2().printError(0));