1. (简答题)(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 Demo18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array :");
int row = sc.nextInt();
int column=sc.nextInt();
double [][] array = new double[row][column];
System.out.println("Enter the array :");
for (int i = 0; i < row; i++) {
for (int i1 = 0; i1 < column; i1++) {
array[i][i1]=sc.nextDouble();
}
}
int[] location = locateLargest(array);
System.out.println("The location of the largest elements is at ("+location[0]+","+location[1]+")");
}
public static int[] locateLargest(double[][] a){
int [] location = {0,0};
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
if(a[location[0]][location[1]]<a[i][j]){
location[0]=i;
location[1]=j;
}
}
}
return location;
}
}
2. (简答题)(Largest row and column) Write a program that randomly fills in 0s and 1s into a 4-by-4 matrix, prints the matrix, and finds the first row and column with the most 1s. Here is a sample run of the program:
0 0 1 1
0 0 1 1
1 1 0 1
1 0 1 0
The largest row index: 2
The largest column index: 2
public class Demo19 {
public static void main(String[] args) {
int [][]matrix= new int[4][4];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j]=(int)(Math.random()*2);
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
int maxR=0;
int maxC=0;
int row = 0;
int col=0;
for (int i = 0; i < matrix.length; i++) {
int numR=0;
int numC=0;
for (int j = 0; j < matrix[i].length; j++) {
if(matrix[i][j]==1){
numR++;
}
if(matrix[j][i]==1){
numC++;
}
}
if (numR>maxR){
maxR=numR;
row = i;
}
if(numC>maxC){
maxC=numC;
col=i;
}
}
System.out.println("The largest row index: "+row);
System.out.println("The largest column index: "+col);
}
}