java - Return the index of the largest number in the array -
question: write method called largest takes array nums3 parameter. finds largest of numbers in array , returns index value of method.
so know if return largest, that's value, how can return i, index? when compile, error: cannot find symbol i.
public static int largest(int[] nums3) { int largest = nums3[0]; for(int i=0; < nums3.length; i++) { if(nums3[i] > largest) { largest = nums3[i]; } } return i; }
one way can saving largest index, not value. need return value in case of empty array:
public static int largest(int[] nums3) { if (nums3.length == 0) { return -1; } int largestindex = 0; for(int i=0; < nums3.length; i++) { if(nums3[i] > nums3[largestindex]) { largestindex = i; } } return largestindex; }
Comments
Post a Comment