1

我一直在为链接列表项目编写构造函数时遇到问题,并且似乎无法弄清楚为什么 charAt 在这种情况下不起作用。我收到一个错误:在调用 charAt 时找不到符号。

   //copy
    public Project123(Project123 s){
        this.head = null;
        for (int i = s.length()-1; i>=0; i--){
            head = new charNode (s.charAt(i), head);
            }
        }
   //constructor
    public Project123(String s){
        this.head = null;
        for (int i = s.length()-1; i>=0; i--){
            head = new charNode (s.charAt(i), head);
            }
        }

我似乎没有与其他相关帖子相同的问题。它是小写的,似乎也被正确调用了。如果需要更多上下文,我会发布更多。

4

4 回答 4

1

在:

  public Project123(Project123 s){
    this.head = null;
    for (int i = s.length()-1; i>=0; i--){
        head = new charNode (s.charAt(i), head);
        }
    }

s.charAt(i)

这里 s 不是一个字符串,所以你不能在它上面使用 String 方法——不会工作。

相反,在该复制构造函数中,遍历复制节点的节点。如果您要进行深拷贝或浅拷贝,这取决于您。

于 2013-10-29T02:05:38.977 回答
0

A Project123 is not a String, so it won't have String methods.

But you've repeated yourself, which is poor coding anyway, so I would chain my constructors:

public Project123(Project123 p) {
    this(p.node.str); // not sure what you've called fields
}

Assuming here that node is the name of the field that holds the value.

于 2013-10-29T02:33:04.453 回答
0

您的两个方法实际上是构造函数。首先,s被声明为一个Project123,而不是一个String。所以,它没有charAt方法。实际上,您的(新更改的)复制构造函数需要不同的技术来克隆它。获取列表中的每个节点,克隆它,然后使用克隆。我不是要使用Cloneable.

哦,更改charNodeCharNode,更改Project123CharLinkedList或类似的东西。

于 2013-10-29T02:08:35.650 回答
0

中的第一个“s”s.charAt(i)不是字符串,而是 Project123。第二个应该没问题。只是改变:

public Project123(Project123 s){

public Project123(String s){
于 2013-10-29T02:06:19.577 回答