簡體   English   中英

以下方法有什么問題?

[英]What is wrong with the method below?

以下是Java方法的代碼,但無法編譯。 我正在使用Eclipse,每當我嘗試編譯代碼時,它都會說:

此方法必須返回int類型的結果。

a,b,c已被聲明為int ,因此返回類型為int

public static int f(int a, int b, int c) { 
    if ((a < b) && (b < c))
        return a; 
    else    if ((a >= b) && (b >= c))
        return b;
    else    if ((a == b) || (b == c) || (a == c))
        return c; 
}

if條件並非詳盡無遺。 如果a > bb < c ,則所有條件都不匹配,並且您的函數將不返回任何內容,這就是Eclipse抱怨的原因。

在末尾添加默認的return語句,不帶條件或在else塊中。

基本上不會編譯,因為如果沒有正確的情況,則沒有else子句。 然后該方法沒有返回值。 因此,編譯器要求返回int。

public static int f(int a, int b, int c) { 
        if ((a < b) && (b < c))
            return a; 
        else    if ((a >= b) && (b >= c))
            return b;
        else    if ((a == b) || (b == c) || (a == c))
            return c; 
        else{
             System.out.println("No clause matched");
             return 0;  //or something else
         }

    }

如果非if-else障礙物開火怎么辦? 如果您錯過了return語句,可以使用這種方式

public static int f(int a, int b, int c) {
        int result = 0 ;
        if ((a < b) && (b < c))
            result = a;
        else    if ((a >= b) && (b >= c))
            result = b;
        else    if ((a == b) || (b == c) || (a == c))
            result = c;
        return result;
    }

創建一個返回點,然后在方法的主體中嘗試為此指定一個相應的值,最后返回它。

如前所述,您的函數可以不返回而結束。 如果這一定不會發生(條件之一應該始終為真),那么您也可以以異常結尾:

public static int f(int a, int b, int c) throws Exception
{
    if ((a < b) && (b < c))
    {
        return a;
    }
    else if ((a >= b) && (b >= c))
    {
        return b;
    }
    else if ((a == b) || (b == c) || (a == c))
    {
        return c;
    }
    throw new Exception("Input not valid");
}

這樣,調用方可以處理Exception或記錄發生問題的日志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM