#Factorial (learning java). Second if statement breaks the code. No error codes. Thank you in advance

11 messages · Page 1 of 1 (latest)

ancient cargo
#

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Give a number: ");
    int number = Integer.valueOf(scanner.nextLine());
    int fact = 1;
    int i = 1;

    while (true) {
        if (number == 0) {
            break;
        }
        if (i <= number) {
            fact = fact * i;
            i++;
        }
    }
    System.out.println("Factorial: " + fact);

}

}

stuck pecanBOT
#

This post has been reserved for your question.

Hey @ancient cargo! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

cedar zephyr
#

you might want to add an else there to break out of the loop

ancient cargo
#

that def worked, thank you!!
so a break is always needed to get out of the while loop? i thought a false statement inside the while loop would break it.

i even tried a *while (i <= number) { * and that didnt work either

stuck pecanBOT
cedar zephyr
ancient cargo
#

i tried this and the code broke multiple times!! now it works....
for loops are the next lesson (not hw, doing helsinki free online course).
tho, I will try the for loop with the added constraint of number = 0 -> fact =1

#

thank you very much for your time!!

stuck pecanBOT
# ancient cargo thank you very much for your time!!

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

ancient cargo
#

just tried it 4 different ways, 2 fors and 2 whiles, all passed, thank you so much!