简体   繁体   中英

Computer Science: Java MC

private int[] myStuff;
/** Precondition: myStuff contains int values in no particular order.
  /*/ 
public int mystery(int num)
{
    for (int k = myStuff.length-1; k>=0; k--)
    {
        if (myStuff[k] < num)
        {
           return k;
        }
    }
return -1;
}

Which of the following best describes the contents of myStuff after the following statement has been executed?

int m = mystery(n); 

Answer: All values in positions m+1 through myStuff.length-1 are greater than or equal to n.

Can anyone explain why this answer is correct? I'm not sure what they mean by contents but, I concluded that myStuff is unchanged because the code doesn't alter the value of myStuff.

Precondition says, that myStuff contains integer values in no particular order. The for loop is initialized with k equal to the lenght of myStuff minus one (since array indices start at zero), iterates while k is greater than or equal to zero and subtract one from k in each iteration.

If you look at the if statement, it will return the current value of k , when the value at the corresponding index of myStuff[k] is less than n ; hence all values in array indices greater than the returned value plus one, must be greater than or equal to n . And if no numbers integers in myStuff are greater than n , minus one is returned.

I hope this helps.

Btw - you're right that the content of mySyuff isn't changed.

You are correct that myStuff is unchanged. However, they are asking about the relationship between the data in the array, the return value of the function, and the function's arguments.

The code does the following:

  • Iterates the array in reverse order. (for loop)
  • At each index during the iteration, it checks the value of that index against n , returning the current index if n is larger. (if statement)

So what does the method return? It returns the first index from the end where mystuff[m] < n . ( mystuff[i] >= num )

The question about the content is valid. It has nothing to with whether the content itself was changed.

This method returns either a non-negative number when there is such k (from myStuff.length-1 to 0 ) that myStuff[k] is less than n , or -1 when all elements of myStuff are more than or equal to n .

Let's consider both cases:

  • m is non-negative number - it means that position m was the last from the right that satisfied the condition myStaff[m] < n , your answer is correct

  • m is -1 - it means that all elements are more than equal than m+1 (which in this case is 0 ) - hence the answer is correct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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