Technical Help & Discussion > Website Design & Programming
Lost calculating factorial
Reno:
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.
sam:
umm I dont know much about Java but the structure looks good, maybe someone else will be able to be more indepth....
Reno:
Took me about 3 more hours that night but, i finally figured it out.
sam:
out of interest what was wrong?
Reno:
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.
Navigation
[0] Message Index
[#] Next page
Go to full version