I have written the following method to find the location/index of the smallest number within the array.
private static int indexOfMin( int[] a, int cnt )
{
int loc = 0;//the variable that will hold the index position
int min = a[loc];//the variable that will compare the value of loc against its location
for (int i = 1; i < a.length; i++)
{
if (a[i] < min )//if value is less
{
min = a[i];// make value of i equal to min
loc = i; loc takes on value of the index of the value of min
}
}
return loc ;
}
Instead of returning the location of the smallest int, it returns the location of the last int. How do I find the location of the smallest int and return it into int loc?
FURTHER EDITS: This is the program in it's entirety. The other two methods I'm still working on. So ignore them.
public static void main (String[] args) throws Exception
{
final int CAP = 20; // capacity
Scanner infile = new Scanner( new File(args[0]) );
int[] arr = new int[ CAP ];
int count = 0;
while ( count < arr.length && infile.hasNextInt() )
{
arr[ count ] = infile.nextInt();
count++;
}
infile.close();
printArray( arr, count );
// this method is given to you as as. don't modity it
int minVal = minOf( arr, count );
System.out.println( "Smallest number is: " + minVal);
// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMin METHOD
int indOfMin = indexOfMin( arr, count );
System.out.println( "Smallest number is located at index position: " + indOfMin );
// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR maxOf METHOD
int maxVal = maxOf( arr, count );
System.out.println( "Largest number is: " + maxVal);
// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMax METHOD
int indOfMax = indexOfMax( arr, count );
System.out.println( "Largest number is located at index position: " + indOfMax );
} // END main
// GIVEN AS IS - DO NOT MODIFY
private static int minOf( int[] a, int cnt )
{
int min = a[0];
for ( int i=0 ; i<cnt ; i++ )
{
if (a[i] < min)
min = a[i];
}
return min;
}
// YOU WRITE DEFINTION OF indexOfMin
// returns the INDEX of the min value NOT the min value itself
private static int indexOfMin( int[] a, int cnt )
{
int loc = 0;
int min = a[loc];
for (int i = 1; i < a.length; i++)
{
if (a[i] < min )
{
min = a[i];
loc = i;
}
}
return loc ;
}
The date file contains the following information:
86 95 84 94 32 8 56 51 98 20 90 1 75 6 21
cntand why is it ignored?