Question

I need to create factorial code with if, else statement, where user input must be WHOLE POSITIVE NUMBER GREATER THAN ZERO. Otherwise it will shows an error message to ask user for entering whole positive number greater than zero. I started with this code:

System.out.print("Enter your number: ");
    int number = sc.nextInt();

    if (number<=0)
        {
            for (count=1; count<=number; count++)
            factorial = factorial*count;

            System.out.println("Factorial of your number is: "+factorial);
            System.out.println();
        }
    else
    {
        System.out.println("Enter a positive whole number greater than 0");
        System.out.println();
    }

The code is working fine for the factorial and error message for entering zero or negative number. So the only thing I need is to define the WHOLE number for the error message.

Was it helpful?

Solution

It seems that yor are putting the wrong condion for the if loop for the number As if(number<=0) will take all number less than or equal to 0,but as per your condition you want a number greater than 0,so change the code as below::

 try{
   System.out.print("Enter your number: ");
   int number=sc.nextInt();
    }catch(Exception ex)  {
       System.out.pritnln("please enter a valid number");
       ex.printStackTrace();
    }


if (number>0)
    {
        for (count=1; count<=number; count++)
        factorial = factorial*count;

        System.out.println("Factorial of your number is: "+factorial);
        System.out.println();
    }
else
{
    System.out.println("Enter a positive whole number greater than 0");
}

OTHER TIPS

Simply put a try block around your call to nextInt(), and if an exception is thrown, tell the user, like so:

int number = 0;
boolean ok = true;
try {
    number = sc.nextInt();
} catch (Exception ex) { //user did not enter a valid integer
    ok = false;
}

if (number>0 && ok) {
    //...
} else {
    System.out.println("Enter a positive whole number greater than 0");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top