gpt4 book ai didi

java - 调用 toString 方法时遇到问题

转载 作者:行者123 更新时间:2023-12-01 13:50:00 24 4
gpt4 key购买 nike

我的方法locateLargest()如下所示,是一种查找数组中最大值的坐标的方法。当我尝试在主方法中使用locateLargest 方法调用toString 方法时,出现错误:无法从LocationTest 类型对非静态方法locateLargest(int[][]) 进行静态引用。不知道如何解决这个问题。

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(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 + "]";
}

}

最佳答案

函数 locateLargest() 是非静态的,因此您无法从 static 函数(例如 main())调用它。将 locateLargest() 更改为 static,因为它似乎没有使用任何实例变量。

您看到编译错误的原因是不允许静态函数调用非静态函数。

关于java - 调用 toString 方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com