LargestInArray.java.html

  1  import java.util.Scanner;
  2  
  3  /**
  4     This program reads a sequence of values and prints them, marking the largest value.
  5  */
  6  public class LargestInArray
  7  {
  8     public static void main(String[] args)
  9     {  
 10        final int LENGTH = 100;
 11        double[] values = new double[LENGTH];
 12        int currentSize = 0;
 13  
 14        // Read inputs
 15  
 16        System.out.println("Please enter values, Q to quit:");
 17        Scanner in = new Scanner(System.in);
 18        while (in.hasNextDouble() && currentSize < values.length)
 19        {  
 20           values[currentSize] = in.nextDouble();
 21           currentSize++;
 22        }
 23  
 24        // Find the largest value
 25  
 26        double largest = values[0];
 27        for (int i = 1; i < currentSize; i++)
 28        {
 29           if (values[i] > largest)
 30           {
 31              largest = values[i];
 32           }
 33        }
 34  
 35        // Print all values, marking the largest
 36  
 37        for (int i = 0; i < currentSize; i++)
 38        {  
 39           System.out.print(values[i]);
 40           if (values[i] == largest) 
 41           {
 42              System.out.print(" <== largest value");
 43           }
 44           System.out.println();
 45        }
 46     }
 47  }