2015-04-06 65 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.