如果使用小数点,则为错误消息的代码

时间:2015-01-20 14:03:47

标签: java if-statement decimal

作为程序的一部分,我写作是一个选项,用户输入一个数字来获得facotrial。到目前为止我有这个:

number = Integer.parseInt(JOptionPane.showInputDialog("\nPlease enter the number you wish to obtain the factorial for"));
    JOptionPane.showMessageDialog(null, "You entered the number: " + number);


    count = (number - 1);

    if(number > 1)
    {

    do

    {

    factorial = number * count;
    JOptionPane.showMessageDialog(null, number + " * " + count + " = " + factorial);
    count--;
    number = factorial;

    }

    while(count > 0);

    JOptionPane.showMessageDialog(null, number + " * " + count + " = " + factorial);

    JOptionPane.showMessageDialog(null, "The facorial of " + number + " is " + factorial);

    }

    else if (number == 0)

    {

    JOptionPane.showMessageDialog(null, "Factorial of 0 is 1");

    }

    else if (number == 1)

    {

    JOptionPane.showMessageDialog(null, "Factorial of 1 is 1");

    }

    else if (number < 0)

    {

    JOptionPane.showMessageDialog(null, "Please enter a number equal to or greater than 0");

这样工作正常,但简要说明还包括一条错误消息,提示用户在使用十进制数字时输入一个整数,如果输入了一个字母。我正在努力编写代码来实现这一目标。

提前致谢

赖安

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式来确保数字不是小数

if (!"wrong_number".matches("^-?\\d+$")) {
    //error
}

除此之外,永远不要假设您的输入是正确的,请务必先检查以后再进行转换:)

答案 1 :(得分:0)

问题是当输入无效时,Integer.parseInt会抛出异常,从而导致方法流程中断。解决这个问题的诀窍是将Integer.parseInt的调用移到代码正文中,在那里你可以处理由无效输入引起的任何异常。您可以将输入存储到String中,并在解析时捕获异常:

String input = JOptionPane.showInputDialog("\nPlease enter the number you wish to obtain the factorial for");
number = -1;
try {
    number = Integer.parseInt(input);
} catch (NumberFormatException nfe) {
    ... // Show a message here saying that "input" is invalid
}

请注意try / catch块。 NumberFormatExceptionInteger.parseInt在您传递无效输入时抛出的内容。