Problem
My professor is super strict and just want to know if I have solved this correctly.
Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as a double type.
Write the following method that returns the location of the largest element in a two-dimensional array:
public static Location locateLargest(double[][] a)
The code is:
public static void main(String[] args) {
System.out.println("Please enter the row and column size");
int row = kk.nextInt();
int column = kk.nextInt();
System.out.println("Enter the values between 1 and 10");
double[][] d = getArray(row,column);
Location l = locateLargest(d);
System.out.println(l.toString());
}
public static double[][] getArray(int row,int column){
double [][] a = new double[row][column];
double input;
for (int i=0;i<a.length;i++){
for (int j=0;j<a[i].length;j++){
a[i][j] = kk.nextDouble();
}
}
return a;
}
public static Location locateLargest(double[][] a){
int rowIndex=0;
int columIndex=0;
double max = a[rowIndex][columIndex];
for (int i=0;i<a.length;i++){
for (int j=0;j<a[i].length;j++){
if (a[i][i]>max) {
max = a[i][j];
rowIndex=i;
columIndex=j;
}
}
}
return new Location(rowIndex,columIndex,max);
}
}
class Location{
int row,column;
double maxValue;
Location(){
}
Location(int row,int column,double maxValue){
this.row = row;
this.column = column;
this.maxValue = maxValue;
}
public String toString(){
return "The largest value is "+maxValue+" at row "+row+" and column "+column;
}
}
Solution
- The class
Location
must be apublic class Location
since it doesn’t make sense to have apublic
method with a non-public
return type. - The fields of the
Location
class must bepublic int
andpublic double
, since the task description​ says so. - The fields of the
Location
class should bepublic final int
andpublic final double
since they won’t change after being initialized once. - The no-arguments constructor then contains a compilation error and should be removed completely.
- You should let the IDE format your code so that it is nice to read:
Ctrl+Shift+F
in Eclipse, orCtrl+Alt+L
in IntelliJ. - Your implementation is completely correct, congratulations.