给出下面的第一个代码。创建Turtle类的正确方法是什么? -基本上,我试图使它不显示错误:Turtle t = new Turtle(STARTX, STARTY, w);
我认为我的问题可能与重载构造函数有关:public Turtle (double STARTX, double STARTY, Class w )
import java.awt.*; //import color;
public class PA1{
//These are constant values that you can use
private static final int STARTX = 100;
private static final int STARTY = 100;
private static final int CHAR_WIDTH = 100;
private static final int CHAR_HEIGHT = 100;
private static final int CHAR_SPACING = 50;
public static void main(String[] args){
//set the width and height of the world
int width = 1000;
int height = 1000;
World w = new World(width, height);
//create a turtle at the starting x and starting y pos
Turtle t = new Turtle(STARTX, STARTY, w);
//Set the turtle pen width.
t.setPenWidth(15);
//This is just an example. Feel free to use it as a reference.
//draw a T
//Assume that the turtle always starts in the top left corner of the character.
t.turn(90);
t.forward(CHAR_WIDTH);
t.backward(CHAR_WIDTH/2);
t.turn(90);
t.forward(CHAR_HEIGHT);
//Move the turtle to the next location for the character
t.penUp();
t.moveTo(STARTX+CHAR_WIDTH+CHAR_SPACING*1, STARTY);
t.penDown();
//WRITE YOUR CODE HERE
}
}
我创建了2个新类:
public class World {
//World w = new World(width, height);
private double defaultWidth;
private double defaultLength;
public World () {
defaultWidth = 0.0;
defaultLength = 0.0; }
public World (double width, double length){
defaultWidth = width;
defaultLength = length; }
public double getWidth () {
return defaultWidth; }
public double getLength () {
return defaultLength; }
public void setWidth (double width){
defaultWidth = width; }
public void setLength(double length){
defaultLength = length; }
}
和
public class Turtle {
// Turtle t = new Turtle(STARTX, STARTY, w);
private double defaultSTARTX;
private double defaultSTARTY;
//private double defaultW;
public Turtle () {
defaultSTARTX = 0.0;
defaultSTARTY = 0.0;
//defaultW = 0.0;
}
public Turtle (double STARTX, double STARTY, Class w ){
defaultSTARTX = STARTX;
defaultSTARTY = STARTY;
//defaultW = w;
}
public double getSTARTX () {
return defaultSTARTX; }
public double getSTARTY () {
return defaultSTARTY; }
public void setSTARTX (double STARTX){
defaultSTARTX = STARTX; }
public void setSTARTY(double STARTY){
defaultSTARTY = STARTY; }
}
答案 0 :(得分:0)
如果您确实需要将World对象传递给Turtle对象,则应将Turtle构造函数定义为:
public Turtle (double STARTX, double STARTY, World w ){
defaultSTARTX = STARTX;
defaultSTARTY = STARTY;
defaultW = w;
}
另外,您必须声明“ w”不是像在某些时候所做的那样两倍,而是在Turtle中声明为“ World”类变量:
private World defaultW;
通过传递Class
作为构造函数参数,您试图传递通用类定义,而不是任何类的Object
实例。差异很细微,但确实存在,并且是您最有可能遇到的问题。
答案 1 :(得分:0)
我在您上面提供的代码中发现了许多问题。我不知道这是否是完整的代码。我试图解决您代码中的所有问题-与您的构造函数和其他Java标准相关。以下为我工作-
Serializable
希望它可以解决您的查询。 快乐的编码。 :)