Home » Java » java – Factorial static method-Exceptionshub

java – Factorial static method-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am making a factorial calc with static methods I’ve been able to make it work with one int at a time but the scanner needs to be able to take two ints (N and M) where the code executes the factorial of all numbers from N up to M.

Here is my code so far

import java.util.Scanner;
public class Factorial {

  public static long Factorialcalc(int n) {
    long fact = 1;
    for (int i = 1; i <= n; i++) {
      fact *= i;
    }
    return fact;
  }
  public static void main(String args[]) {
    System.out.println("Enter first int N");
    Scanner sc = new Scanner(System.in);
    int n;
    long fact = 1;
    n = sc.nextInt();
    System.out.println("Enter second int M");
    int m;
    m = sc.nextInt();
    if (n < 0) {
      System.out.println("Not Valid!");
    } else {
      for (int i = n; i <= m; i++) {
        fact = Factorialcalc(i);
      }
      fact = Factorialcalc(n);
      System.out.println("the factorial for " + n + " is " + fact + ".");
    }
  }
}

I’m not sure how I should go about adding in the M int for it to calculate the factorial from N upwards.

How to&Answers:

in main method following changes required:

int m = sc.nextInt()

in else block:

for (int i=n;i<=m;i++){
    fact = Factorial.Factorialcalc(i);

}

Tip: Always add your code as a Code Sample or Snippet (HTML/CSS/JS)