我有以下代码:
public class Rectangle extends java.awt.Rectangle
{
private Position position;
public Rectangle(Rectangle toCopy)
{
this.position = toCopy.position;
}
public Rectangle(Position position, int width, int height)
{
super(width, height);
this.position = position;
}
这很好用,但我需要宽度和高度才能浮动。问题是java.awt.Rectangle中的构造函数接受宽度和高度的int类型。有没有办法在构造函数中使宽度和高度浮动?
答案 0 :(得分:2)
我相信你正在寻找casting
。这样您就可以将float
变成int
。您的示例中的实现将是:
public Rectangle(Position position, float width, float height) // Changed types to float
{
super((int) width, (int) height); // Cast from float to int
this.position = position;
// width & height are floats, like requested
}
答案 1 :(得分:0)
使用如下所示的转换将int转换为浮点数:float myfloat = (float) myInt;
所以改变这个:
public Rectangle(Position position, int width, int height)
{
super(width, height);
this.position = position;
}
To This:
public Rectangle(Position position, int width, int height)
{
super((float) width,(float) height);
this.position = position;
}
答案 2 :(得分:0)
也许你可以试试这个:
int i;
float f = i * 1.0f;