简体   繁体   中英

Getting a Java factorial program with a while loop to keep repeating if the user enters with “y” and has the factorial part working as well

I am new to programming and I am trying to figure out how to get a java program to correctly run a factorial and ask the user if they would like to continue and input another number to use and display the factorial for that one. When the user inputs "y", the program is supposed to then ask for another number. If they select "n", the program should terminate. I've been working on this code for a day and still haven't figured out where I am going wrong in the code to make it solve factorials correctly while looping. Can someone please help me?

  int i = 0; int factorial = 1; int input; char ind = 'y'; while (ind == 'y') { System.out.println("Please enter in a number to determine it's factorial: "); input = scan.nextInt(); scan.nextLine(); if ( i<= input) { i=input; i++; factorial = factorial * i; System.out.println(" the factorial of: " + input + " is " + factorial); }System.out.println(" Do you want to continue? (y/n) :"); ind = scan.nextLine().charAt(0); } System.out.println("goodbye."); } } 

Okay, first, you need to know what a factorial is.

n! = n * (n-1)!

That's important to understand. The factorial if 5 is 5 times the factorial of 4. That's actually kind of cool and very useful. So you can write a function that does that.

long factorial(long n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n-1);
}

So what you do is define a method similar to the above. And then in your loop where you ask them to enter a number, you call this method. It calls itself as needed to do the calculation for you.

There are other ways. You can do a for-loop.

long result = 0;
for (long val = 2; val <= n; ++val) {
    result = result * val;
}

But the recursive method is kind of cool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM