gpt4 book ai didi

java - 限制 float 参数的允许值

转载 作者:行者123 更新时间:2023-12-01 11:38:54 26 4
gpt4 key购买 nike

我是 Java 新手,正在开发管理日程的程序。

是否可以限制作为函数参数的float的值?

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

最佳答案

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

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

}

}

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

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

关于java - 限制 float 参数的允许值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29718654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com