You are here: Home Lecture 1 Simple Factorial.java

Factorial.java

Python Source icon Factorial.java — Python Source, 760 bytes

File contents

import java.io.*;

public class Factorial {

    /*@ requires n >= 0;
      @ ensures  \result > 0;
      @*/
    public static int factorial(int n) {
	int result = n;
	while (--n > 0) {
	    result *= n;
	}
	return result;
    }


    public static void main(String[] param) throws IOException {
	while (true) {
	    BufferedReader reader = 
		new BufferedReader(new InputStreamReader(System.in));
	    System.err.print("Compute factorial of: ");
	    try {
		String input = reader.readLine();
		if (input.equals("q"))
		    return;
		int value = Integer.parseInt(input);
		int result = factorial(value);
		System.err.println("The result is: "+result);
	    } catch (NumberFormatException ex) {
		System.err.println("Invalid Number: "+ex);
	    }
	}
    }

}