Sponsor for PC Pals Forum

Author Topic: Lost calculating factorial  (Read 2758 times)

Offline Reno

  • Established Member
  • ****
  • Posts: 1294
  • bob
Lost calculating factorial
« 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.

Offline sam

  • Administrator
  • *****
  • Posts: 19402
Lost calculating factorial
« Reply #1 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....
- sam | @starrydude --



Offline Reno

  • Established Member
  • ****
  • Posts: 1294
  • bob
Lost calculating factorial
« Reply #2 on: October 10, 2006, 00:55 »
Took me about 3 more hours that night but, i finally figured it out.

Offline sam

  • Administrator
  • *****
  • Posts: 19402
Lost calculating factorial
« Reply #3 on: October 10, 2006, 09:19 »
out of interest what was wrong?
- sam | @starrydude --



Offline Reno

  • Established Member
  • ****
  • Posts: 1294
  • bob
Lost calculating factorial
« Reply #4 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.

Offline sam

  • Administrator
  • *****
  • Posts: 19402
Lost calculating factorial
« Reply #5 on: October 10, 2006, 17:55 »
ok... glad you fixed it!
- sam | @starrydude --




Show unread posts since last visit.
Sponsor for PC Pals Forum