3

他の Node クラスと連携する LString (リンク リスト クラス) というクラスがあります。文字シーケンスをトラバースして小文字を大文字に変換する toUppercase() メソッドを作成しました。

私の問題は戻り値の型です。これは、多くのコーディングを行うときに発生するように思われる問題です。return LString入力しても変数として認識され、同じ互換性のない型のエラーが発生するため、必要な 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
public LString toUppercase(){
      Node current = front;
      while(current != null){
         current.data = Character.toUpperCase(current.data);
         current = current.next;
      }
      return front;
}

frontタイプは です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 に答える