PC Pals Forum

Technical Help & Discussion => Website Design & Programming => Topic started by: Reno on October 08, 2006, 17:21

Title: Lost calculating factorial
Post by: Reno on October 08, 2006, 17:21
import java.util.Scanner;
public class Factorial {
  
    public static void main(String[] args) {
       Scanner bob = new Scanner(System.in);
       System.out.println("Please enter your integer.");
        int factorial = bob.nextInt();
        int counter = factorial;
        while (counter == 0)
           factorial = factorial * (counter - 1);
           counter--;
       System.out.println(factorial);
    }}

This is in java. Could someone tell me why it doesn't work.
Title: Lost calculating factorial
Post by: sam on October 09, 2006, 10:05
umm I dont know much about Java but the structure looks good, maybe someone else will be able to be more indepth....
Title: Lost calculating factorial
Post by: Reno on October 10, 2006, 00:55
Took me about 3 more hours that night but, i finally figured it out.
Title: Lost calculating factorial
Post by: sam on October 10, 2006, 09:19
out of interest what was wrong?
Title: Lost calculating factorial
Post by: Reno on October 10, 2006, 13:10
import java.util.Scanner;
public class Factorial {
  
    public static void main(String[] args) {
       Scanner bob = new Scanner(System.in);
       System.out.println("Please enter your integer.");
        int factorial = bob.nextInt();
        int counter = factorial - 1;
        while (counter > 1)
           {
          factorial = factorial * counter;
          counter--;
               }
       System.out.println(factorial);
    }}

// (bob1>1) { factorial*=bob1; bob1--; }

Thats the answer

I was under the impression that the loop repeated only when the answer was wrong. I also had to subtract 1 from factorial before going into the loop or the answer would be 5*5*4*3*2*1 = 600 instead of 5*4*3*2*1.
Title: Lost calculating factorial
Post by: sam on October 10, 2006, 17:55
ok... glad you fixed it!