go to previous page   go to home page   go to next page highlighting

Answer:

What is the parameter of the method that calculates factorial?

The value of N, an integer

What is the return value of the method that calculates factorial?

The factorial of N.

Stub

Here is the class including a complete static main() method and a stub for factorial()

import  java.util.Scanner;

// User repeatedly enters integer N.  
// Calculate and print N factorial.
// User enters a negative value to exit.

public class FactorialTester
{
  
  // Calculate num factorial
  public static long factorial( int num )
  {
     return 1L;
  }
  
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    long fact; 
    int N;

    System.out.println( "To exit, enter a negative value" );
    System.out.print( "Enter N: " );
    N = scan.nextInt();

    while ( N <= 0 )
    {
      fact = factorial( N );
      System.out.println( "factorial is " + fact );
      System.out.print( "Enter N: " );
      N = scan.nextInt();
    }
     
  }
}

The factorial method in this program is just a stub.

A stub is an incomplete version of a method that is used in place of the full method. Stubs are extremely useful when developing programs. The above program can be compiled and run to test that main() works correctly. This is another aspect of modularity: test individual modules as soon as they are written. Don't wait until the entire program is written and try to test everything at once.


QUESTION 5:

Let's check that main() is working:

C:\Source> javac FactorialTester.java
C:\Source> java FactorialTester
To exit, enter a negative value
Enter N: 12
C:\Source>

Oh No! Something is wrong! The program exits immediately when a positive number is entered.

Where is the mistake?


go to previous page   go to home page   go to next page