2015-04-06 116 views
0

我是java的初學者......如果語句後面跟着else語句,直到找到一個評估爲true的語句,我已經看到了很多這樣的例子。但是在這個程序中,兩個語句(if和else if)都被評估。爲什麼?否則if語句

public int centeredAverage(int[] nums) { 

    int[] nums = {1, 1, 5, 5, 10, 8, 7}; 

    int sum = 0; 
    int centered = 0; 
    int min = nums[0]; 
    int max = nums[0]; 
    int i = 0; 

    for (i = 0; i < nums.length; i++){ 
     if (nums[i] < min){ 
      min = nums[i]; 
     } else if (nums[i] > max){ 
      max = nums[i]; 
     } 
     sum += nums[i]; 
     centered = ((sum-max-min)/(nums.length-2)); 
    } 

    return centered; 
} 
+0

它總是執行else塊。 Wats錯誤? – Pratik 2015-04-06 04:12:22

+0

沒什麼。我只是想通過編寫許多不同的代碼來完全理解if和if是如何工作的。所以,你說在評估「if」之後,那麼總是會評估「else if」?謝謝! – 2015-04-06 04:15:56

+0

看起來不像'if'和'else'將被評估。你能給我們一些輸出嗎? – 2015-04-06 04:16:10

回答

3

因爲他們是在一個循環改變i等改變nums[i]等改變什麼if的是真實的。

0

您傳入的雙引號稱爲nums,並在方法中定義了一個相同名稱的數組,這看起來很奇怪。您的for循環的起始索引也應該是1

+0

開始索引應該爲零,而不是1.這是Java。 – 2015-04-06 04:17:32

+0

我相信dmonarch會提供一個優化,因爲min和nums [0]開始都是一樣的。這僅僅是因爲它不會讓新手程序員混淆。 :)他的名字'nums'也是。出於某種原因,你不會給你的孩子同名。 – CandiedOrange 2015-04-06 04:21:29

-1

If語句的後面跟着else的工作 - 如果在這裏很好。我們在這裏得到預期的結果。 if和else-if語句都沒有執行。根據邏輯,只有該語句執行爲TRUE。 在這裏,我們可以使用「System.out.println」來識別程序的工作。代碼和控制檯輸出如下:

int[] nums = {1, 1, 5, 5, 10, 8, 7}; 

    int sum = 0; 
    int centered = 0; 
    int min = nums[0]; 
    int max = nums[0]; 
    int i = 0; 

    for (i = 0; i < nums.length; i++) 
    { 
     if (nums[i] > min) 
     { 
      min = nums[i]; 

      System.out.println("inside first if: " + i); 
      // taking value of i in SOP to get the iteration value 

     } 
     else if (nums[i] > max) 
     { 
      max = nums[i]; 
     } 

     sum += nums[i]; 
     centered = ((sum-max-min)/(nums.length-2)); 

     System.out.println("inside else if: " + i); 
     // taking value of i in SOP to get the iteration value 

    } 

    System.out.println("centered value " 
      + " " + centered); 

您可以在每個程序中很好地使用SOP來獲取執行順序。

0
Im guessing this is the same problem from codingbat, next time copy and paste the problem desciption for others! 

public int centeredAverage(int[] nums) { 
     Arrays.sort(nums); //sorts the array smallest to biggest 
     int total = 0; 
     //nums is already sorted, so the smallest value is at spot 0 
     //and the biggest value is at the end. 
     for(int a = 1; a < nums.length - 1; a++){ //avoid the first and last numbers 
     total += nums[a]; 
     } 
     return total/(nums.length - 2); //need () so we can substract 2 first 

     //Another way could simply sum all the elements then subtract from that sum 
     //the biggest and smallest numbers in the array, then divide by nums.length- 2, it is a 
     //little more complex, but allows a for : each loop. 
    } 

But for you, well since you are a beginner, restate your strategy (algorithm), find the smallest and biggest numbers in the array, subtract that out of the sum of all elements in the array then divide that number by nums.length - 2, since we are ignoring 2 numbers.