可以将整数变成双(包装程序类)

发布于 2025-02-06 05:50:55 字数 664 浏览 5 评论 0原文

我尝试创建一个函数,如果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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鱼窥荷 2025-02-13 05:50:56

问题是您正在使用参考类型(包装类类)而不是原始类型。从intdouble有效的铸件,但铸造从Integer to double不进行。因此,您将需要找到其他方法来转换它。

由于您定义t扩展了数字,因此可以使用号码的任何方法 x 和y

因此,请使用以下内容,而不是施放double

public static<t extends Number> double rand(t x,t y) {
  double a = x.doubleValue();
  double b = y.doubleValue();

The problem is that you are working with reference types (wrapper classes) instead of primitive types. A cast from int to double works, but a cast from Integer to Double 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 of Number for x and y.

So instead of casting to double, use this:

public static<t extends Number> double rand(t x,t y) {
  double a = x.doubleValue();
  double b = y.doubleValue();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文