2

I don't understand why only my while statement is working and it does not move on to the for statement for the valid integer.

import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {
        long posNumber;
        long x;
        long fact = 1;

        do {
            System.out.print("Enter a number between 2 and 15: ");
            Scanner in = new Scanner(System.in);
            posNumber = in.nextLong();
        } while (posNumber >= 2 || posNumber <= 15);


        for (x = 1; x <= posNumber; x++)
            fact = fact*x;
            System.out.println("Factorial of " +posNumber+ " is " +fact);

        }

    }
2
  • It's in your for loop's condition. It should be posNumber < 2 || posNumber > 15. Commented Dec 14, 2014 at 4:02
  • Every number is either greater than 2 or less than 15 (and some numbers are both). So what you wrote is equivalent to while (true). Commented Dec 14, 2014 at 4:22

2 Answers 2

1

You should try something like, if you plan to get numbers in a loop:

Scanner in = new Scanner(System.in);
do {
    System.out.print("Enter a number between 2 and 15: ");
    posNumber = in.nextLong();

    for (x = 1; x <= posNumber; x++)
      fact = fact*x;
      System.out.println("Factorial of " +posNumber+ " is " +fact);
    }
} while (posNumber >= 2 || posNumber <= 15);

Or you can change the condition (in case to run it just once):

while (posNumber < 2 || posNumber > 15);
Sign up to request clarification or add additional context in comments.

Comments

0

You want your program to continue asking the user if the number is invalid. That means if it is less than 2 or greater than 15. Replace your while condition with:

do {
    ...
} while (posNumber < 2 || posNumber > 15);

If the user enters a 1, posNumber < 2 will evaluate to true causing the loop to repeat and ask for a new number.

If the user enters 3, both posNumber < 2 and posNumber > 15 will evaluate to false and the loop will break and then your for loop will execute.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.