3

我有一个名为 LString 的类(一个链表类),它与我的其他 Node 类一起使用。我写了一个 toUppercase() 方法,它遍历字符序列并将小写转换为大写。

我的问题是返回类型,这是我在编写很多代码时似乎遇到的问题。我不确定如何返回所需的 LString 类型,因为即使我键入return LString它也会将其识别为变量并给出相同的不兼容类型错误。

这是显式错误:

    LString.java:134: error: incompatible types
      return current;
             ^
  required: LString
  found:    Node

如何在我的方法中返回这种必需的 LString 类型?

我对 Java 还很陌生,在写这篇文章时,掌握返回类型对我来说似乎很麻烦。让我知道我是否应该发布我的整个班级。如果我的问题有点不清楚,也请告诉我,我想对这个论坛的用户简明扼要。

正如这里所要求的,我的更多代码指定了我在两个类中所做的声明。

我的节点类:

      public class Node{
       public char data;
       public Node next;

       //constructors from page 956
       public Node()
       {
          this('\0',null);  //'\0' is null char for java
       }

       public Node(char initialData, Node initialNext)
       {
          data = initialData;
          next = initialNext;
       }
}

还有我的 LString 类(我将仅列出构造函数和我的 toUppercase 方法):

public class LString{

   private Node front = null;  //first val in list
   private Node back;   //last val in list
   private int size = 0;
   private int i;

   public LString(){
      //construct empty list
      Node LString = new Node();
      front = null;

   }
   public LString toUppercase(){
      Node current = front;
      while(current != null){
         current.data = Character.toUpperCase(current.data);
         current = current.next;
      }
      return front;
   }
}

如果我需要提供更多信息,请告诉我。

4

2 回答 2

1

要返回所需的内容,LString只需执行以下操作:

return this;

因为LString是包含链表第一个节点的类,所有修改链表的方法都应该简单地返回它。另请注意,此行在构造函数中没有做任何事情,您可以将其删除:

Node LString = new Node();
于 2013-11-21T22:46:54.463 回答
1
public LString toUppercase(){
      Node current = front;
      while(current != null){
         current.data = Character.toUpperCase(current.data);
         current = current.next;
      }
      return front;
}

front是 type Node,但是方法的签名是public LString toUppercase(),这意味着它应该返回一个LString实例。

想想你真正想要返回的是什么。你想返回一个LString包含大写字符的,对吧?但这已经是您正在使用的实例!所以你可以返回this

public LString toUppercase(){
      Node current = front;
      while(current != null){
         current.data = Character.toUpperCase(current.data);
         current = current.next;
      }

      return this;
}

但在这种情况下,您仍然需要另一种打印大写字符的方法:

LString lString = new LString();
...
...
lString.toUppercase(); //lString is already modified and contains uppercase characters! You
                       //don't have to "return" anything. If you returned "this" this
                       //line would be lString = lString.toUppercase(), but that's
                       //not buying you anything special.
System.out.println(lString.toString()); //Assuming you have a toString method 
                                        //that prints out the characters.

通过调用toUppercase实例方法,您已经修改了您的LString实例,因此实际上不需要返回任何内容。

于 2013-11-21T23:20:26.583 回答