简体   繁体   中英

Creating factorial - if, else statement with error messages in java

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM