2014-09-12 49 views
0

這不是應該返回正確的值嗎?因爲它特別定義了int[] temp?但是,它表示temp未解決。因此我必須在if之內放入另一個退貨temp並更改else聲明中的最後return,因此有兩個退貨。如果我在if和else中設置了值,我不能將它返回給外部嗎?適當的地點上的返回

public int[] maxEnd3(int[] nums) { 

    if (nums[0] > nums[2]) { 
     int[] temp = {nums[0],nums[0],nums[0]}; 
    } 
    else { 
     int[] temp= {nums[2],nums[2],nums[2]}; 
    } 
    return temp; 
} 

回答

2

您沒有在正確的範圍內聲明temp。 試試這個:

public int[] maxEnd3(int[] nums) { 
    int []temp = new int[3]; 
    if (nums[0] > nums[2]) { 
     temp[0] = nums[0]; 
     temp[1] = nums[0]; 
     temp[2] = nums[0]; 
    } 
    else { 
     temp[0] = nums[2]; 
     temp[1] = nums[2]; 
     temp[2] = nums[2]; 
    } 
    return temp; 
} 

或者這樣:

public int[] maxEnd3(int[] nums) { 
    int []temp; 
    if (nums[0] > nums[2]) { 
     temp = new int[]{nums[0],nums[0],nums[0]}; 
    } 
    else { 
     temp = new int[]{nums[2],nums[2],nums[2]}; 
    } 
    return temp; 
} 

在聲明它的if語句中,這僅僅是報關行和右括號之間有效。

+0

哦,非常感謝你,我已經知道了 – 2014-09-12 21:48:51