Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中操作数组。困在困难的家庭作业上_Java_Arrays - Fatal编程技术网

在Java中操作数组。困在困难的家庭作业上

在Java中操作数组。困在困难的家庭作业上,java,arrays,Java,Arrays,我是Java的新手,这学期在编程课程中学习Java。我们有一个家庭作业要交,我正在努力。我很感激这对有经验的程序员来说是很容易的,但对我来说这是个难题。这是第一个问题 公共整数计数范围[]数据,整数低,整数高 为此,您必须计算数组中位于>>lo到hi(包括lo到hi)范围内的元素数data,然后返回计数。例如,如果数据是数组{1,3,2,5,8}>>,则调用 countInRangedata,2,5 应返回3,因为有三个元素3、2和5位于范围2内。。五, 以下是我迄今为止所做的工作: /**

我是Java的新手,这学期在编程课程中学习Java。我们有一个家庭作业要交,我正在努力。我很感激这对有经验的程序员来说是很容易的,但对我来说这是个难题。这是第一个问题

公共整数计数范围[]数据,整数低,整数高

为此,您必须计算数组中位于>>lo到hi(包括lo到hi)范围内的元素数data,然后返回计数。例如,如果数据是数组{1,3,2,5,8}>>,则调用

countInRangedata,2,5

应返回3,因为有三个元素3、2和5位于范围2内。。五,

以下是我迄今为止所做的工作:

/**
 * Count the number of occurrences of values in an array, R, that is
 * greater than or equal to lo and less than or equal to hi.
 *
 * @param  data  the array of integers
 * @param  lo   the lowest value of the range
 * @param  hi   the highest value of the range
 * @return      the count of numbers that lie in the range lo .. hi
 */
public int countInRange(int[] array, int lo, int hi) {
    int counter = 0; 
    int occurrences = 0;
    while(counter < array.length) {
        if(array[counter] >= lo) {
            occurrences++; 
        }
        counter++;
    }
    return occurrences;
}

因为作业的原因,我没有输入代码。我给了一个指针。

您的if语句中缺少上限检查

for ( int i = 0; i < array.length; i++ ) {
    if ( array[i] >= lo && array[i] <= hi ) {
        occurrences++;
    }
}

使用for语句来迭代数组。

对于java中的数组和集合,您可以使用a,尤其是在学习时,更少的代码通常更容易理解,因为剩下的代码只是重要的内容

另一方面,如果您想构造自己的循环,请始终使用for循环-在while循环中更新不必要的循环变量被认为是糟糕的风格,因为这会导致严重的错误

答案很简单,很难让你从神秘的暗示中找到答案:

public int countInRange(int[] array, int lo, int hi) {
    int occurrences = 0;
    for (int element : array) {
        if (element >= lo && element <= hi) {
            occurrences++;
        }
    }
    return occurrences;
}

只是一个与你的问题无关的提示。尝试使用for语句迭代数组;在Java中,每个都有一个增强的for-too,在某些情况下甚至更好,包括您的情况。解决问题,我会发布一些代码;那么:问题是什么?请接受其中一个答案作为您问题的答案,如果它对您有帮助,请向上投票。当有人花时间帮助你时,这是你能做的最起码的事。你问了六个问题,都得到了答案,但从来没有接受过一个。非常感谢每一个帮助你的人。我已经弄明白了,并对未来提出了一些好的建议。干杯
public int countInRange(int[] array, int lo, int hi) {
    int occurrences = 0;
    for (int element : array) {
        if (element >= lo && element <= hi) {
            occurrences++;
        }
    }
    return occurrences;
}