限制float参数的允许值

时间:2015-04-18 14:30:57

标签: java types arguments

我是Java的新手,我正在制作管理计划表的程序。

是否可以限制float的值,这是函数的参数?

由于这是一个时间表,因此小时的值必须介于024之间。

1 个答案:

答案 0 :(得分:1)

一个简单的异常处理示例是:

     class ValidateDouble {

        public static void main(String[] args) {

        // Your initial value
        double value = 0;
        System.out.println("Your initial value is: " + value);

        // Not valid argument, should print 0 as returned from method
        value = inputDouble(-1);
        System.out.println("After entering -1, your value is: " + value);

        // Not valid argument, should print 0 as returned from method
        value = inputDouble(-1.5);
        System.out.println("After entering -1.5, your value is: " + value);

        // Not valid argument, should print 0 as returned from method
        value = inputDouble(25);
        System.out.println("After entering 25, your value is: " + value);

        // Valid argument, should print the returned argument value
        value = inputDouble(2);
        System.out.println("\nAfter entering 2, your value is: " + value);

        // Valid argument, should print the returned argument value 
        value = inputDouble(2.54);
        System.out.println("\nAfter entering 2.54, your value is: " + value);

    }

    private static double inputDouble (double number) {

        // Program will try to execute this
        try {

            // If number is out of range, throw exception if not, return the argument.
            if (number < 0 || number > 24) {
                throw new IllegalArgumentException("\nNot a valid argument...");
            } else {
                return number;
            }

        } catch (IllegalArgumentException exception) {

            // Print message thrown in the exception and return 0.
            System.out.println(exception.getMessage());
            return 0;
        }

    }

}

我知道这可能不是你想要的,我已经根据你的问题发布了一个例子,如何验证方法参数。有很多方法可以验证您的用户输入,但只要您询问验证方法参数,我认为这可以帮助您实现目标。欢呼声。

您将无法在方法原型中执行此操作。