196k views
4 votes
Consider the following instance variable and incomplete method.

The method getSmallest should return the smallest value in tRay.

private int[] tRay; //assume the tRay contains values

public int getSmallest()
{
int small = Integer.MAX_VALUE;

/* code */

return small;
}

Which of the following code segments shown below could be used to replace
/* code */ so that getSmallest will work as intended?

I.
for( int i=0; i if( tRay[i] < small )
small = tRay[i];

II.
for( int item : tRay )
if( tRay[item] < small )
small = tRay[item];

III.
for( int item : tRay )
if( item < small )
small = item;

1 Answer

2 votes

Final answer:

The correct code segment to replace the incomplete code in the getSmallest method is Option III.

Step-by-step explanation:

The correct code segment to replace code in the given method is Option III: for (int item : tRay) if (item < small) small = item;

This code segment iterates over each item in the array tRay and compares it with the current value of small. If the current item is smaller than small, it updates small to the smaller value.

Options I and II are incorrect because they use the index value i and item respectively as the index to access the array elements, which would result in an ArrayIndexOutOfBoundsException in this case.

User Abellina
by
8.0k points