Pages

Sunday, 28 August 2016

Chapter 8 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*8.13 (Locate the largest element) Write the following method that returns the location of the largest element in a two-dimensional array. public static int[] locateLargest(double[][] a) The return value is a one-dimensional array that contains two elements. These two elements indicate the row and column indices of the largest element in the two-dimensional array. Write a test program that prompts the user to enter a two- dimensional array and displays the location of the largest element in the array.
Here is a sample run:

    Enter the number of rows and columns of the array: 3 4
    Enter the array: 
    23.5 35 2 10
    4.5 3 45 3.5
    35 44 5.5 9.6
    The location of the largest element is at (1, 2)  

import java.util.Scanner;
 
 
 
public class ProgrammingEx8_13 {
 
 public static void main(String[] args) {
  java.util.Scanner input = new Scanner(System.in);
 
  System.out
    .print("Enter the number of rows and columns of the array:");
  int i = input.nextInt();
  int j = input.nextInt();
  int[] intResult;
System.out.println("Enter the array:");
  double[][] in = new double[i][j];
 
  for (int k = 0; k < i; k++) {
   for (int k2 = 0; k2 < j; k2++) {
    in[k][k2] = input.nextDouble();
   }
  }
   
  intResult = locateLargest(in);
  System.out.println("The location of the largest element is at (" + intResult[0] + ", " + intResult[1] + ")");
 
 }
 
 public static int[] locateLargest(double[][] a) {
  double dblMax = 0;
  int[] intReturn = new int[2];
 
  for (int k = 0; k < a.length; k++) {
   for (int k2 = 0; k2 < a[k].length; k2++) {
    if (a[k][k2] > dblMax) {
     dblMax = a[k][k2];
     intReturn[0] = k;
     intReturn[1] = k2;
    }
   }
  }
  return intReturn;
 }
}

No comments :

Post a Comment