gpt4 book ai didi

java - 面向对象的 Java 点和方法继承

转载 作者:行者123 更新时间:2023-11-30 03:14:33 24 4
gpt4 key购买 nike

现在我有几个类(class):

文件1

package simplestart;

import simplegui.SimpleGUI;
public class Point {
int x, y;
public Point(int a, int b){
this.x = a;
this.y = b;
}
public void drawLine(Object data, SimpleGUI sg){
Node current = new Node(data);
}
public int getX(){
return x;
}
@Override
public String toString(){
return(x + " " + y);
}
}

文件2

package simplestart;
import simplegui.SimpleGUI;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SimpleStart {
public static void main(String[] args){
int x, y;
SimpleGUI sg = new SimpleGUI();
sg.setTitle("Shape Abstraction");
sg.centerGUIonScreen();
LinkedList l1 = new LinkedList();
File fl = new File("shapelist.txt");
Scanner scan = new Scanner(fl);
while(scan.hasNext()){
x = scan.nextInt();
y = scan.nextInt();
Point p = new Point(x, y);
l1.insertFirst(p);
}
l1.traverseList(l1, sg);
l1.abstractList(l1, sg);
}
}

文件3

package simplestart;
public class Node {
Object data;
Node next;

public Node(Object data){
this.data = data;
}
}

文件4

package simplestart;

import simplegui.SimpleGUI;

public class LinkedList {
Node START;
public LinkedList(){
START = null;
}
public void insertFirst(Object data){
Node n = new Node(data);
n.next = START;
START = n;
}

public void traverseList(Object data, SimpleGUI sg){
Node current = START;
int x, y, ex, ey;
while(current != null){
//This is where I'm trying to pull the data from Class Point
//The error that appears is can't find symbol int x
x = current.data.x;
y = current.data.y;
ex = current.next.data.x;
ey = current.next.data.y;
sg.drawLine(x, y, ex, ey);
//toString() is an override method in Class Point
System.out.println(current.data);
//However, this doesn't work... which I don't get cause it's also a method in Class Point like toString()
current = current.next;
}
}
public void abstractList(Object data, SimpleGUI sg){
Node current = START;
Node temp = START;
current = current.next;
int lp, pr, rl, s;
while(current.next != null){
lp = current.next.data.x ­ current.data.x;
pr = current.next.next.data.x ­ current.next.data.x;
rl = current.next.next.data.x ­ current.data.x;
s = lp + pr ­ rl;
current.next.data = s;
temp = current.next;
current = current.next.next;
}
}
}

基本上,我在文件 1 中取一个点,以文件 3 中节点的形式将这些点添加到文件 2 中的链接列表中,并在文件 4 中迭代它们。但是,当 current.data 应该是每个节点时对于点,我无法访问方法“getX()”,甚至无法访问 current.data.x。我很好奇为什么会这样,但我一生都无法弄清楚。任何帮助都是非常必要的!

最佳答案

无法访问数据上的点的原因是 Nodedata 属性是 Object 类型。

如果您想获得该属性(property),您可以例如

  • 将属性转换为Point

    ((Point)current.data).x

  • 引入您自己的 Node 类,该类具有 Point 类型的属性(也可以是通用的)

正如 Andy 指出的,我还强烈建议实现您自己的节点类。这样做的优点是,您将获得语言支持,并且不需要进行转换,并且如果您的节点数据类型发生更改,您将不会遇到运行时异常 - 编译器会告诉您。

关于java - 面向对象的 Java 点和方法继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32942151/

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