简体   繁体   English

创建阶乘-在Java中使用错误消息的if,else语句

[英]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. 我需要使用if,else语句创建阶乘代码,其中用户输入的绝对数字必须大于零。 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:: 看来,侑是把错误的condion的,如果循环的number作为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");
}

Simply put a try block around your call to nextInt() , and if an exception is thrown, tell the user, like so: 只需在对nextInt()调用周围放置一个try块,然后如果引发异常,请告诉用户,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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