【问题标题】:incompatible types: possible lossy conversion from double to int. I don't know why i'm getting this error message不兼容的类型:从 double 到 int 的可能有损转换。我不知道为什么我会收到此错误消息
【发布时间】:2016-10-27 00:45:10
【问题描述】:
    private void buildingComposotion () 

{
    for (int i=1; i<=randomInteger(3,6); i++)
    {
        int numberOfStories = 2;
        buildingFrame(numberOfStories);
        buildingWindows(numberOfStories);
    }
}
private int randomInteger(int min, int max) 
{
    min = (int) Math.ceil(min);
    max = (int) Math.floor(max);
    return Math.floor(Math.random() * (max - min));
}

错误“不兼容的类型:从 double 到 int 的可能有损转换。”在第 15 行。

【问题讨论】:

  • 您无需致电Math.ceil(min)Math.floor(max)。这些值已经是整数。您还需要在返回值中添加min

标签: java casting int double


【解决方案1】:

Math.floor 返回 double,而不是 int。修改你的randomInteger 方法:

private int randomInteger(int min, int max) 
{
    min = (int) Math.ceil(min);
    max = (int) Math.floor(max);
    return (int) Math.floor(Math.random() * (max - min));
}

或者,使用Random 类中的nextInt

【讨论】:

  • 太棒了,感谢您的快速回复!这是我第一次使用堆栈溢出,我从来没有想过会有这么快的回复。干杯!
猜你喜欢
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
相关资源
最近更新 更多