如下所示,我的方法 locateLargest() 是一种在数组中查找最大值坐标的方法。我无法将返回值放入 toString 方法。我不知道如何将其格式化为 toString 方法。
public Location locateLargest(int[][] x){
int maxValue = getMax(x);
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x.length; j++)
if (x[i][j] == maxValue)
return new Location(i,j);
}
}
我的 toString 尝试:
public String toString(){
return "[" + i + "][" + j + "]";
}
位置类代码:
class Location {
private int row;
private int column;
Location(){}//end constructor
Location(int row, int column){
this.row = row;
this.column = column;
}//end arg constructor
public int getRow(){
return this.row;
}
public int getColumn(){
return this.column;
}
这是我的程序的完整代码:
import java.util.Scanner;
public class LocationTest {
public static void main(String[] args) {
Scanner numberInput = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array: ");
int row = numberInput.nextInt();
int column = numberInput.nextInt();
Location l1 = new Location(row, column);
Location l2 = new Location();
row = l1.getRow();
column = l1.getColumn();
int[][] array = new int[l1.getRow()][l1.getColumn()];
System.out.println("Please enter the array elements: ");
for (int r = 0; r < array.length; r++){
for (int c = 0; c < array[r].length; c++){
array[r][c] = numberInput.nextInt();
}//end nested loop
}//end for loop
System.out.println(getMax(array));
System.out.println(l1.locateLargest(array).toString());
}
public static int getMax(int[][] x){
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x[i].length; j++){
if (x[i][j] > max)
max = x[i][j];
}
}
return max;
}
public Location locateLargest(int[][] x){
int maxValue = getMax(x);
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x.length; j++)
if (x[i][j] == maxValue)
return new Location(i,j);
}
return null;
}
}
class Location {
private int row;
private int column;
Location(){}//end constructor
Location(int row, int column){
this.row = row;
this.column = column;
}//end arg constructor
public int getRow(){
return this.row;
}
public int getColumn(){
return this.column;
}
public String toString(){
return "[" + row + "][" + column + "]";
}
}