该函数实际上返回什么?

时间:2019-04-23 14:51:10

标签: java

我是Java的初学者。在这段代码中,我无法理解此函数实际返回的内容。是否返回j的最大值。如果返回的是j的最大值,那么返回的j是多少?在for循环中执行,它在哪里返回j的值?

public static int nextIndex(int[] pages, int i) {
    int page = pages[i];

    for (int j = i+1; j < pages.length; j++) {
        if (pages[j] == page) {
            return j;
        }
    }

    return Integer.MAX_VALUE;
}

2 个答案:

答案 0 :(得分:3)

逐行:

int page = pages[i];

我们将int变量页面设置为等于函数中指定索引处的页面

for (int j = i+1; j < pages.length; j++) {

我们从函数调用参数中指定的i索引之后的数组索引开始循环遍历

    if (pages[j] == page) {
        return j;
    }

如果找到一个int值,则将页面变量设置为-返回索引(也就是找到该值的数组中的点)

return Integer.MAX_VALUE;

默认情况下-如果我们无法在数组i的后面通过i索引找到与变量page相同值的值,则返回Integer.MAX_VALUE。

答案 1 :(得分:0)

Think of it using an analogy. Let's say the integer array "pages" is an array which holds the number of words on the pages. Let's say we have 100 pages so the size of pages array would be 100. Your function takes as argument the pages array and the an integer representing the page number.

nextIndex() is effectively trying to find out the next page whose number of words is equal to the number of words on the page represented by "i"(one of the arguments to your method).

So if you passed i as 20, you're trying to find out the next page after the 20th page which has the same number of words as the 20th page.

If the method doesn't find any page having the same number of words as page i, it returns a default MAX_VALUE(this is where the analogy kinda falls apart, going by my analogy I would've returned -1 indicating that we didn't find any page that matched but that's deviating from the issue here)