可以将整数变成双(包装程序类)
我尝试创建一个函数,如果x和y是整数,则在x和y之间返回随机int,但是如果x或y是双倍的函数,则函数在x和y之间返回双倍。但是,当我尝试使用整数时,它会出现一个例外:
“类java.lang.integer不能被施放到类java.lang.double(java.lang.integer和java.lang.lang.lang.lang.doubes中
我如何修复它?
public class Test {
public static void main(String[] args) {
System.out.print(rand(10,12.0));
}
public static<t extends Number> double rand(t x,t y) {
double a = (double) x;
double b = (double) y;
b = a < b ?(a + (b - a) * Math.random()):(b + (a - b) * Math.random());
return (x instanceof Double || y instanceof Double) ? b : (int) b;
}
}
I tried to create a function which return a random int between x and y if x and y are integer but if x or y is a double the function return a double between x and y. But when I try with a integer it throw an Exception:
"class java.lang.Integer cannot be cast to class java.lang.Double (java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap')"
how can I fix it?
public class Test {
public static void main(String[] args) {
System.out.print(rand(10,12.0));
}
public static<t extends Number> double rand(t x,t y) {
double a = (double) x;
double b = (double) y;
b = a < b ?(a + (b - a) * Math.random()):(b + (a - b) * Math.random());
return (x instanceof Double || y instanceof Double) ? b : (int) b;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您正在使用参考类型(包装类类)而不是原始类型。从
int
到double
有效的铸件,但铸造从Integer
todouble
不进行。因此,您将需要找到其他方法来转换它。由于您定义
t扩展了数字
,因此可以使用号码
的任何方法 x 和y
。因此,请使用以下内容,而不是施放
double
:The problem is that you are working with reference types (wrapper classes) instead of primitive types. A cast from
int
todouble
works, but a cast fromInteger
toDouble
doesn't. So you will need to find some other way to convert this.Since you define
t extends Number
, you can use any method ofNumber
forx
andy
.So instead of casting to
double
, use this: