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에서 메소드의 이름을 지정하고 정의하는 방법을 이해해야 합니다.

함수를 선언하는 간단한 예를 들어보겠습니다. 우리의 함수는 두 개의 숫자를 더할 것이고 정수 값이 될 답을 반환할 것입니다.

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

public은 멤버의 액세스를 알리는 데 사용되는 Java에서 예약된 키워드입니다. 이 경우 공개됩니다.

이 키워드 뒤에는 메서드/함수의 반환 유형이 옵니다. 이 경우 int입니다. 그런 다음 함수의 이름을 작성하고 예약된 키워드가 아닌 한 원하는 단어가 될 수 있습니다.

위의 기능은 잘 작동하며 오류가 발생하지 않습니다. 그러나 오류 invalid method declaration; return type required는 함수의 반환 유형 추가를 놓쳤을 때 발생합니다.

반환 유형 대신 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