Experiment 3
Experiment 3
台州学院
电子与信息工程学院实验报告
NOTE:
When pasting code, please do not use a black background. Otherwise, when the
teacher prints your assignments at the end of the semester, it will be a mess of
black.
实验日期: 2024 年 6 月 19 日
Problem Description:
(Exercise08_13) Write the following method that returns
the location of the largest element in a two-dimensional
array.
<Output>
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)
<End Output>
Analysis: (Describe the problem including input and output in your own
words.)
This Java program is designed to find the location (row and column indices) of the
largest element in a given two-dimensional array. Here's a breakdown of how the
program works:
Input:
The user is prompted to enter the number of rows and columns for the array.
Then, the user is asked to input the elements of the 2D array row by row.
Processing:
The program creates a 2D array (matrix) based on the specified number of rows
and columns.
The user inputs the elements into this array.
The locateLargest method is called, which iterates over the elements of the array
to find the largest value. It keeps track of the row and column indices where this
maximum value is found.
Output:
The program prints out the location (row and column indices) of the largest element in
the array.
Coding: (Copy and Paste Source Code here. Format your code using Courier
10pts)
import java.util.Scanner;
public class Exercise_8_13{
public static void main(String[] args) {
//Create a scanner
Scanner scanner = new Scanner (System.in);
System.out.print("Enter the number of the rows and columns of
the array: ");
byte rows = scanner.nextByte();
byte columns = scanner.nextByte();
if (rows <1 || columns<1) {
System.err.print("Error : Invalid rows or columns.");
System.exit(0);
}
double[][] matrix = new double [rows][columns];
System.out.println("Enter the array : ");
for(byte i = 0; i < rows; i++)
for(byte j = 0; j < columns; j++)
matrix[i][j] = scanner.nextDouble();
//Close Scanner
scanner.close();
}
public static int[] locateLargest (double[][] a) {
int [] location = new int [2];
double max = a[0][0];
for(int row = a.length-1; row >= 0; row--){
for (int column = a [a.length-1].length-1; column>=0;
column--){
if(max < a[row][column]) {
location[0] = row;
location[1] = column;
max = a[row][column];
}
}
}
return location;
}
}