John Jones
John Jones

Reputation: 23

Java do while validation

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);

        }

    }

Upvotes: 2

Views: 3493

Answers (2)

carloabelli
carloabelli

Reputation: 4349

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.

Upvotes: 0

nitishagar
nitishagar

Reputation: 9403

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);

Upvotes: 1

Related Questions