修復 Java 無效方法宣告;需要返回型別

Haider Ali 2022年1月14日
修復 Java 無效方法宣告;需要返回型別

無效的方法宣告;需要返回型別。當你宣告一個函式並且沒有提及它的返回型別時,Java 中會發生這種型別的錯誤。

讓我們繼續瞭解 Java 中函式和方法的基礎知識。

修復無效的方法宣告;需要返回型別在 Java 中

你需要了解如何在 Java 中命名和定義方法。

讓我們舉一個簡單的例子來宣告一個函式。我們的函式將兩個數字相加,並返回一個整數值的答案。

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

public 是 Java 中的保留關鍵字,用於告知成員的訪問許可權。在這種情況下,它是公開的。

此關鍵字後跟方法/函式的返回型別。在這種情況下,它是 int。然後你寫下函式的名稱,它可以是你選擇的任何單詞,只要它不是保留關鍵字。

上面的函式可以正常工作,並且你不會收到任何錯誤。但錯誤無效的方法宣告; 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
Author: 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