gpt4 book ai didi

java - 找不到 z 变量(3D 点 - Java 24 小时)

转载 作者:行者123 更新时间:2023-11-30 07:57:22 25 4
gpt4 key购买 nike

我刚刚开始学习 Java,如果这是一个菜鸟问题,我很抱歉,但我已经浏览了每一行代码,但我不明白出了什么问题。代码来自《24小时Java》一书。

代码的目的是获取起始 2D 和 3D 点,然后移动它们并平移它们。首先它要求我创建一个 3D 点类:

package com.java24hours;

import java.awt.*;

public class Point3D extends Point
{
public int z;

public Point3D(int x, int y, int z)
{
super(x,y);
this.z = z;
}
public void move(int x, int y, int z)
{
this.z = z;
super.move(x,y);
}
public void translate(int x, int y, int z)
{
this.z += z;
super.translate(x,y);
}
}

然后它调用一个测试器类,该类使用 Points3D 来移动和平移 3D 点:

package com.java24hours;

import java.awt.*;

class PointTester
{
public static void main(String[] arguments)
{
Point location1 = new Point(11,22);
Point location2 = new Point3D(7,6,64);

System.out.println("The 2D point is at ("+location1.x + "," + location1.y +")");

System.out.println("It's being moved to (4,11)");
location1.move(4,11);
System.out.println("The 2D point is now at (" + location1.x + "," + location1.y + ")");

System.out.println("It's now being moved -10 in both the x and y axis");
location1.translate(-10,-10);
System.out.println("The 2D point is now at (" + location1.x +"," + location1.y + ")\n");

System.out.println("The 3D point is at (" + location2.x + "," + location2.y + "," + location.z + ")");

System.out.println("It's being moved to (10,22,71)");
location2.move(10,22,71);
System.out.println("The 3D point is now at (" + location2.x + "," + location2.y + "," + location2.z + ")");

System.out.println("It's now going to be moved -20 units in the x y and z axis");
location2.translate(-20,-20,-20);
System.out.println("It's now at (" + location2.x + "," + location2.y + "," + location2.z + ")");
}
}

这会在包含 location2.z 的行上产生以下错误:

找不到符号方法 move 不能应用于给定类型方法翻译不能应用于给定类型

来源在这里: https://www.informit.com/library/content.aspx?b=STY_Java2_24hours&seqNum=140

这大致就是它应该给我的内容(我更改了一些措辞):

The 2D point is located at (11, 22) 
It's being moved to (4, 13)
The 2D point is now at (4, 13)
It's being moved -10 units on both the x and y axes
The 2D point ends up at (-6, 3)

The 3D point is located at (7, 6, 64)
It's being moved to (10, 22, 71)
The 3D point is now at (10, 22, 71)
It's being moved -20 units on the x, y and z axes
The 3D point ends up at (-10, 2, 51)

我认为我的困惑是我在 Point3D 类中声明了 z 变量,我创建了接受三个变量的 newPoint3D,然后当我稍后尝试使用第三个变量时它找不到它。

谢谢

最佳答案

您的代码存在语法问题,因为您使用的是 location.z 而不是 location2.z

此外,您还使用 Point 类作为引用来创建 Point3D 对象。由于多态性概念(我建议您研究一下),您无法从 Point 类访问变量 z 作为 Point3D 继承了 Point 类,因此变量 z 是在 Point3D 类中定义的,而不是在 Point 中定义的。

最后,您应该实例化您的 3D 点,如下所示:

Point3D location2 = new Point3D(7,6,64); 

关于java - 找不到 z 变量(3D 点 - Java 24 小时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com