I have an issue with this fragment of code. It's part of a program that calculates what you would call nPr on some calculators. It compiles with no error but each time I run it and set n = 0 I get a seemingly endless list of error messages. Why can't it just print out "Error!" and terminate the program like I programmed it to?
{
System.out.print("n = ");
int n = j.nextInt();
System.out.print("r = ");
int r = j.nextInt();
long n_fact = factorial(n);
if ( ( (n - r) <= 0 ) || (n <= 0) || (r < 0) )
{
System.out.println("Error!");
System.exit(0);
}
else
{
long nr_fact = factorial(n - r);
long nPr = n_fact / nr_fact;
NumberFormat f = NumberFormat.getNumberInstance();
System.out.println("nPr = " + f.format(nPr));
}
}
You're calling factorial(n)
before checking whether n > 0
. Move the line
long n_fact = factorial(n);
to inside the else
block.
Move this line in else
block:
long n_fact = factorial(n);
as it is getting triggered even when n=0 or n < 0
, as you are checking n > 0
after the above call, which you don't want. I doubt if this(n <=0) is properly handled in your factorial()
method.
Alternatively put the check and handling on n
in your factorial(n)
method ie return 1, if n=0 and error out(throw excepion) if n < 0;
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.