[英]Is it possible to declare variables within a certain interval within Java
Say I have declared a class with a variable, alpha, of type double float.假设我已经声明了一个带有变量 alpha 的类,它的类型为 double float。 Is it in any way possible to define alpha within a certain interval, say (1, 3).
是否可以以任何方式在某个间隔内定义 alpha,例如 (1, 3)。
You can't.你不能。 However if really needed you could create your own Class:
但是,如果确实需要,您可以创建自己的类:
public class FloatWithinInterval {
public static final int LOWER_BOUND = 1;
public static final int UPPER_BOUND = 3;
public final float value;
public FloatWithinInterval(float value) {
if(value < LOWER_BOUND || value > UPPER_BOUND) throw new IllegalArgumentException(); //Or a custom exception
this.value = value;
}
}
Note that thanks to the final
keyword, your value is immutable.请注意,由于使用了
final
关键字,您的值是不可变的。
Then your field would be declared as那么你的领域将被声明为
FloatWithinInterval alpha;
And to initialise it, instead of并初始化它,而不是
alpha = 2.0f;
You would have to write你必须写
alpha = new FloatWithinInterval(2.0f);
And you can access your value with alpha.value
您可以使用
alpha.value
访问您的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.