繁体   English   中英

其他if语句

[英]Else if statements

我是Java的初学者... if语句,然后按else if语句按顺序进行评估,直到找到一个评估结果为true为止,并且我已经看到了许多这样的示例。 但是在该程序中,两个语句(if和else 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;
}

因为它们处于改变i的循环中,所以改变了nums[i] ,因此改变了if为true时的情况。

您通过引用调用了称为nums的double数组,并在方法中定义了一个同名数组,这似乎很奇怪。 另外,您的for循环的开始索引应为1

 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.

If语句后接else-if的工作在这里很好。 我们在这里得到预期的结果。 语句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来获取执行顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM