简体   繁体   中英

Recursive Factorial Java

First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.

Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.

Here is code thus far:

import java.util.Scanner;

public class Recursive
   {
      public static void main(String[] args)
      {
         int number;             // To hold a number
         char letter;            // To hold a character


         //Create a Scanner object for keyboard input
         Scanner keyboard = new Scanner(System.in);

         //Get a number from the user
         System.out.print("Enter an integer to find the factorial: ");
         number = keyboard.nextInt();

         //Display the factorial
         System.out.println(number + "! is " + factorial(number));
      }  

      private static int factorial(int n)

     {
         if (n == 0)
            return 1;     // Base Case
         else if (n > 0)
            return n * factorial(n-1);
         else (!(n>0))
         return
         System.out.println(number + "is invalid");
      }
    }  

After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial

    while (true) {
        // Get a number from the user
        System.out.print("Enter an integer to find the factorial: ");
        int number = keyboard.nextInt();
        if (Pattern.matches("\\d+", String.valueOf(number))) {
            if (Integer.valueOf(number) == 0)
                System.exit(0);

            // Display the factorial
            System.out.println(number + "! is " + factorial(number));
        }
        else
            System.out.println("Error");
    }

My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.

public static void main(String[] args)
  {
     Integer number;             // To hold a number
     String letter;            // To hold a character

     //Create a Scanner object for keyboard input
     Scanner keyboard = new Scanner(System.in);

     //Get a number from the user
     System.out.print("Enter an integer to find the factorial: ");
     while(keyboard.hasNext()){

         letter = keyboard.next();
         try{
             number = Integer.parseInt(letter);
             if(number==0){
                    //Exiting
                    break;
                }
             int fact = factorial(number);
             //Display the factorial
             System.out.println(number + "! is " + fact);
             System.out.print("Enter an integer to find the factorial: ");
            }
         catch(NumberFormatException e){
            System.out.println("Invalid input please enter integers only");
            }
        }
  }  

Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.

My solution for recursive factorial using Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;

class Main {
    public static String factorial(int n,String s){
        if(n>0){
            BigInteger fact = new BigInteger(s);
            fact = fact.multiply(new BigInteger(n + ""));
            return factorial(n-1,fact.toString());
        }
        else{
            return s.toString();
        }
    }

    public static void main(String args[] ) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
            int n = Integer.parseInt(line);
            if(n==0)
            System.out.println("Factorial is 0");
            else{
            String s = factorial(n,"1");
            System.out.println("Factorial is " + s);
            }
    }
}

the example of factorial using recursive in Java

public class MainClass {
    public static void main(String args[]) {
    for (int counter = 0; counter <= 10; counter++){
        System.out.printf("%d! = %d\n", counter,
        factorial(counter));
    }
    }
    public static long factorial(long number) {
        if (number <= 1)
            return 1;
        else
            return number * factorial(number - 1);
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM