在java中创建带有错误消息的factorial - if,else语句

时间:2014-01-12 12:26:49

标签: java if-statement factorial

我需要使用if,else语句创建阶乘代码,其中用户输入必须是大于零的正整数。否则,它将显示一条错误消息,要求用户输入大于零的整数正数。 我从这段代码开始:

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

代码对于输入零或负数的阶乘和错误消息正常工作。所以我唯一需要的是为错误信息定义整数。

2 个答案:

答案 0 :(得分:1)

似乎yor为number的if循环添加了错误的条件 由于if(number<=0)将取所有小于或等于0的数字,但根据您的条件,您希望数字大于0,因此请更改以下代码::

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

答案 1 :(得分:-1)

只需在try的调用周围添加nextInt()块,如果抛出异常,请告诉用户,如下所示:

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