Original Post
I have a problem with one of the exercises of my Java tutorial, i hope someone can give me a good hint and help me with this one. I would appreciate it. The exercise is this: However, I don't know how i can compute the second largest element (in the same for-loop as the largest element) like in the exercise. I hope someone can help me.
Quote:Now i know how to compute the maximum of an array, like this:
Exercise 2 --- Two Largest Elements Complete the following program so that it computes and writes out the two largest elements in the array. import java.io.* ; class TwoLargest { public static void main ( String[] args ) throws IOException { int[] data = {3, 1, 5, 7, 4, 12, -3, 8, -2}; // declare and initialize variables for the two largest // compute the two largest for ( int index= ; index < data.length; index++) { } // write out the two largest System.out.println( ); } }
import java.io.* ;
class Largest
{
public static void main ( String[] args ) throws IOException
{
int[] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};
// declare and initialize variable for the largest
int largest = data[0];
// compute the largest
for ( int index= 0; index < data.length; index++)
{
if(largest < data[index]) {
largest = data[index];
}
}
// write out the largest
System.out.println("The largest is: " + largest);
}
}