r/learnjava • • Jan 27 '23

How to create a factorial in Java

Hi everyone, I was wondering if any of you guys can point me in the right direction when it comes to creating a factorial in Java specifically for the MOOC Helsinki because it's asking me for it but I've read all of the text regarding this (which is not much, if anything) so I don't know if they want it a specific way if there's more than one way to do it. Can anybody who has completed the exercise or knows how about it point me in the right direction on where to look for the solution for this? Thanks!

Update: The result came back as " Your program was trying to read too much user input, remember to use nextLine()!." But it makes no sense because I put "

int number = Integer.valueOf(scanner.nextLine());" which includes the nextLine() in it, so now I'm honestly even more confused now...

1 Upvotes

18 comments sorted by

•

u/AutoModerator Jan 27 '23

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full - best also formatted as code block

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

4

u/TylerMorrisHOU Jan 27 '23

Generally, as long as you properly calculate the factorial, they'll give you credit. Consider: what is a factorial? If I write 3! = 6, how can I verify whether that's correct?

1

u/AutumnAced Jan 28 '23

I just don't understand anything about it because the MOOC barely mentioned and when I looked it up online it showed me something that I couldn't link to the lesson as whatever little WAS mentioned on the lesson had nothing to do with what I saw online. So right not I don't even know where to start looking.

3

u/desrtfx Jan 27 '23

What have you tried?

What specifically do you not understand?

The actual code for the factorial is a 4 liner including initializing the factorial variable and the closing curly brace of the loop.

1

u/AutumnAced Jan 28 '23

I've tried the closest thing out of what I know, which was basically using the 1 + 2 + 3 code but to multiply but I don't think that'll work. Also I don't understand what you mean by 4 liner but I do understand initializing part, is the factorial variable the name I give the input?

2

u/desrtfx Jan 28 '23

is the factorial variable the name I give the input?

No, that's the variable you use to calculate and store the factorial.

The factorial of a number is just the numbers from 1 to the number multiplied. So, if you could manage to do the sum of numbers exercise, the factorial exercise should not be a problem.

1

u/AutumnAced Jan 28 '23

I understand the logic behind, like outside of code, I know how they work and what they are, the problem is (at least I think) that even though at some level the logic is the same "like 1 + 2 + 3 + 4... until [input]" and "1 x 2 x 3 x 4... until [input]" but when it comes to actually coding it, it doesn't seem like it's quite the same, at least when I look up the answer online, because it doesn't follow the same coding logic as 1 + 2 + 3...

also, is a factorial variable something I have to name like a regular variable?

2

u/desrtfx Jan 28 '23

Trust me, the logic is 100% the same, only the mathematical operation changes.

is a factorial variable something I have to name like a regular variable?

It is the same as the "sum" or "totals" variable for the "Sum Of Numbers", so, no, it is not a special variable.

1

u/AutumnAced Jan 28 '23

Is there any source where it is be expanded upon further?

2

u/desrtfx Jan 28 '23

Review this exercise: Part02_17.SumOfASequence

The logic to this exercise is exactly the same as for the factorial. Only the arithmetic operation changes.

1

u/AutumnAced Jan 28 '23 edited Jan 28 '23

Mm I understand, I’ll just start studying from the beginning to get a better grasp on whatever comes before that just in case. I appreciate it!

Edit: So this is the result I got from reading from the beginning and reviewing the exercise and this is what I came up with\

int number = whatever.input; int n = 1;

        if (n == number)  {
            break;
        }

        if (n <= number)  {
            n = n * (n + 1);
            n++;
        }

sout ("factorial" + n)

and it doesn't return anything. I honestly don't know what I'm doing wrong and I've been stuck at this part for about a week. I remember it saying that if I want to use a variable outside of the ifs and whiles, I have to initialize it before opening the if or while and I did (unlike what's written here) but it's not returning anything and I just can't bring myself to figure out why.

Edit #2: the output it gives me is:

"Give a number: " [input 4]

then it asks me again with no return

"Give a number: " [input 4]

etc...

:c

2

u/do11abill Jan 27 '23

How well do you know recursion?

1

u/AutumnAced Jan 28 '23

Absolutely nada, zero, infinitely nothing actually lol. I was introduced to it out of nowhere, basically I was learning 1 + 2 + 3 + 4 etc. and got factorials introduced out of nowhere as just another exercise but what I've seen online makes it look like it deserves its own part . I don't want to look it up online because in the other courses that I've done, looking it up online gives you the answer but not on the way that the course wants you to because I'm guessing you wouldn't be able to learn the lesson that it's meant to teach you then.

2

u/do11abill Jan 28 '23

True. In my experience, factorials have been the most common way to explain how recursion works so I figured that’s what it was trying to teach you. I never took the MOOC courses so I don’t know the full context. I would try as hard as possible to stay the path like you are doing and try to not look up the answer. However, if it is recursion that you are trying to learn, it might benefit to see the answer and reverse engineer how it works. That’s what helped me learn it.

1

u/AutumnAced Jan 28 '23

Do you mean getting the answer and kinda figuring out how it got to the answer instead of trying to get to the answer?

1

u/do11abill Jan 28 '23

Lol something like that.

2

u/8igg7e5 Jan 27 '23

At this point in the course, they are expecting you to use a loop to solve the factorial task. The instructions state that you need to get the factorial limit from the user, and explains that a factorial is multiplying numbers, starting at 1, up to the limit.

So 4! is equal to 1 * 2 * 3 * 4.

So you need to get a number from the user and compute the factorial with a loop, successively updating the result, up to the limit the user supplied.

This is very similar to the Sum of a Sequence exercise (except that you're updating the factorial each loop instead of the sum). Eventually you'll recognise the similarity between an exercise and something you've done before.

1

u/AutumnAced Jan 28 '23

Really? To me they look like completely different things to learn since I've been trying to link it to the other problem but I've been struggling to find the logic with "while [variable a] is greater or equal to [input], make [variable b] += [variable a] then [variable a]++"

So I figured that I needed another variable, but I also struggle to find the stop to place [variable c].