Assignment :: TwoLargestElements
Complete the following program so that it computes and writes out the two largest elements in the array.
So far I have this...and it just gets the largest number for both outputs..I need to change it so I get both the largest and second largest. Any help would greatly be appreciated, thanks!
import java.io.* ;
class TwoLargest {
public static void main ( String[] args )
throws IOException {
int[] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};
int largest = 0, largest2 = 0;
for ( int index = 0; index < data.length; index++)
if(largest < data[index]) {
largest = data [index];
}
for ( int index = 0; index < data.length; index++)
if (largest2 < data[index]) {
largest2 = data [index];
}
System.out.println("The largest number in the array is: " + largest);
System.out.println("The second largest number in the array is: " + largest2);
}
}