如何修复运行时错误并删除java中抽象类的double?



我的程序要求定义一个抽象类,其中包含:

  • 3 个受保护的实例变量:topLeft(类型为 java.awt.Point)、宽度(int 类型)和高度(int 类型)
  • 一个默认(或"无参数"或"无参数")构造函数,它使用默认值构造形状:topLeft = (0, 0)、width=0 和 height=0
  • 使用给定值构造形状的重载构造函数。
  • 一个重写的 toString() 方法,该方法以"(x, y) width x height"格式返回实例的字符串说明
  • 访问器和突变器方法:getX(),getY(),setX(),setY(),getHeight()...
    • 一个 move() 方法,它将左上角点在 X 方向上移动 1 个,在 y 方向上移动 2
    • 一种抽象的绘制方法,通过形状的位置、宽度和高度"绘制"形状。

我尝试输入"int"而不是双精度,但出现错误,说无法转换。

到目前为止,这是完成的

import java.awt.*;
abstract class SimpleMovingShape {
protected Point topLeft;
protected int width;
protected int height;
public SimpleMovingShape() {
topLeft = new Point(0, 0);
width = 0;
height = 0;
}

public SimpleMovingShape(Point topLeft, int width, int height) {
this.topLeft = topLeft;
this.width = width;
this.height = height;
}
public double getX() {
return topLeft.getX();
}
public double getY() {
return topLeft.getY();
}
public void setX(double x) {
topLeft.setLocation(x, topLeft.getY());
}
public void setY(double y) {
topLeft.setLocation(topLeft.getX(), y);
}
public void move() {
topLeft.setLocation(getX() + 1, getY() + 2);
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public void setHeight(int height) {
this.height = height;
}
public void setWidth(int width) {
this.width = width;
}
public void setTopLeft(Point topLeft) {
this.topLeft = topLeft;
}
public Point getTopLeft() {
return topLeft;
}
public abstract void draw();
@Override
public String toString() {
return "(" + getX() + "," + getY() + ") " + getWidth() + " X " 
+ getHeight();
}
}

对于测试人员

SimpleMovingShape r2 = new SimpleMovingRectangle(new Point(10, 20), 
20, 20);
System.out.println(r2.getX());
System.out.println(r2.getY());

输出显示10.0 20.0其中预期输出10 20

对于测试人员,这会显示运行时错误SimpleMovingRectangle r1= new SimpleMovingRectangle();r1.move(); System.out.printf("(%d, %d)", r1.getX(), r1.getY());

***Runtime error***
Exception in thread "main" java.util.IllegalFormatConversionException: 
d != java.lang.Double
at 
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at 
java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at __Tester__.runTests(__Tester__.java:86)
at __Tester__.main(__Tester__.java:80)
public int getX() {
double dbl = topLeft.getX().doubleValue();
return (int) dbl;
}
public int getY() {
double dbl = topLeft.getY().doubleValue();
return (int) dbl;
}
public void setX(int x) {
topLeft.setLocation(x, topLeft.getY());
}
public void setY(int y) {
topLeft.setLocation(topLeft.getX(), y);
}

最新更新