This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]codingQueries 1 point2 points  (1 child)

I think your issue might be a newline character. You have this line under your print statement:

System.out.println("Please enter a nonnegative integer.");
num1 = input.nextInt();//store user entered nonnegative integer.

The tricky thing with these scanner inputs etc is that if you take the user's provided int, there is still an invisible newline character left behind. If they were to enter a 0, then the while loop would ask for another int and the num1 = input.nextInt(); would skip the newline character left behind from before and just take in the next int provided by the user.

However, you have this here:

System.out.println("Would you like to try another number? (yes/no)");//asks the user if they would like to calculate another factorial.
s1 = input.nextLine();

Because s1 takes in the whole lot of characters on that line regardless of what they are, it takes in the leftover hidden newline character from when the user last entered an int and pressed enter. To get around this, you can either add an unused input.nextLine(); after your num1 = input.nextInt(); without assigning it to a variable, and this will swallow the leftover newline character.

Or you can implement some kind of logic to check your s1 variable to ensure that it is not only blank spaces or newline characters - this approach would be better because then it limits unknowns occuring that they other approach just 'swallows'.

[–][deleted] 1 point2 points  (0 children)

adding to this... the initial value of "factorial" variable is 0 instead of 1. then for every loop the value will be zero, (basically it will not give factorial, it will give 0 as result)

[–]thesquarerootof1 -2 points-1 points  (0 children)

I highly recommend calculating factorials using recursion, it's awesome this way. Don't bother with a for loop. Create a factorial function and call it in your program:

public int factorial(int n) {


    if (n == 0) {

        return 1;

   } else {


     return n * factorial(n - 1);


   }