Java エラーInvalid Method Declaration; Return Type Required を修正

Haider Ali 2023年10月12日
Java エラーInvalid Method Declaration; Return Type Required を修正

Invalid method declaration; return type required。このタイプのエラーは、Java で関数を宣言し、その戻りタイプについて言及しない場合に発生します。

Java の関数とメソッドの基本をフォローアップしましょう。

Java エラーInvalid Method Declaration; Return Type Required を修正

Java でメソッドに名前を付けて定義する方法を理解する必要があります。

関数を宣言する簡単な例を見てみましょう。この関数は 2つの数値を加算し、整数値の答えを返します。

public int addTwoNumbers(int a, int b) {
  return a + b;
}

public は、メンバーのアクセスを通知するために使用される Java の予約キーワードです。この場合、それは公開されています。

このキーワードの後に​​は、メソッド/関数の戻りタイプが続きます。この場合、それは int です。次に、関数の名前を記述します。予約語でない限り、任意の単語にすることができます。

上記の関数は問題なく機能し、エラーは発生しません。しかし、エラーinvalid method declaration; return type required 関数の戻りタイプの追加を見逃した場合に発生します。

これを解決するには、return 型の代わりに void を記述します。void は、関数が値を返さないことを示します。

次のコードは避けてください。

public void displaystring(String A) {
  System.out.println(A);
  return A; // wrong way
}

上記のメソッドは void 関数であるため、値を返すことはできません。特定のタスクを実行する必要がある場合は、void 関数を使用しますが、値は必要ありません。

上記のコードを書く正しい方法を以下に示します。

public void displaystring(String A) {
  System.out.println(A);
}

これが完全な自明のコードです。

public class Main {
  public static void main(String args[]) {
    // invalid method declaration; return type required  This
    // Error Occurs When you Declare A function did not mention any return type.

    // there are only two options.
    // if Function Did Not Return Any Value  void Keyword should be used.
    // void function always tell the compiler this function will return nothing..
    Print();
    Print1();
  }
  // e.g of void function...........
  public static void Print() {
    System.out.println(" I am Void Function");
  }
  // e.g of non void Function............

  public static int Print1() {
    System.out.println(" I am Non Void Function");
    return 3;
  }
}

出力:

I am Void Function
I am Non Void Function
著者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

関連記事 - Java Function

関連記事 - Java Error