Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /**
- * This demonstrates calling methods recursively in a language
- * called Java. It does a factorial calculation.
- * @Author: Shaun B
- * @Version: 2012-08-13
- **/
- public class recursive
- {
- // Java seems a little more pedantic and it took me a few minutes of
- // actual thinking to convert this from the much easier to understand
- // programming language 'C'.
- private static long number=0;
- private static long returnValue=0;
- // There are probably better ways to read in keyboard inputs, but this
- // works, so...
- private static Scanner keyboardBuffer=new Scanner (System.in);
- // Our main function:
- public static void main (String args[])
- {
- // User prompts:
- System.out.println ("This is an example of recursive programming");
- System.out.println ("Please enter a whole positive number to see");
- System.out.print ("see its' factorial value, ");
- System.out.println ("or type 0 (zero) to exit.");
- System.out.print ("C:\\>");
- number=keyboardBuffer.nextInt();
- // Checks for zero to exit:
- if (number==0)
- {
- System.out.println ("\n\nHave a nice day :-)");
- return;
- }
- // Converts a negative to a positive number (not sure if it'd make any
- // actual difference though...)
- if (number<0)
- {
- number=-number;
- }
- // Calls the recursive function factorial, sending the entered number to it
- // and storing the returned value in the variable returnValue:
- returnValue=factorial (number);
- System.out.format ("And the answer is %d\n",returnValue);
- // Restarts the program:
- number=0;
- returnValue=0;
- recursive.main (null);
- }
- public static long factorial (long n)
- {
- // Break case:
- if (n==1)
- {
- return n;
- }
- else
- {
- // Calls 'method' recursively:
- return n*factorial (n-1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement