gpt4 book ai didi

java - 如何在一种方法和另一种方法中使用声明的变量。

转载 作者:行者123 更新时间:2023-11-30 03:31:56 25 4
gpt4 key购买 nike

所以我有一个如下所示的方法:

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
int numRows = textmaze.length;
int numCols = textmaze[0].length;
int [][] x = new int[numRows][numCols];
}

所以我想在其他方法中使用变量 x、numRows 和 numCols,但是 numRows 和 numCols 需要必须作为参数传入的 String textmaze,并且调用此方法的主要方法位于我的另一个类中m 不允许修改。那么如何在其他方法中使用这些变量呢?

最佳答案

由于Maze是一个构造函数,并且您想在类的其他部分使用变量,因此您应该将变量改为实例字段,例如...

private int numRows;
private int numCols;
private int [][] x;

public Maze(String[] textmaze, int startRow, int startCol, int finishRow, int finishCol){
numRows = textmaze.length;
numCols = textmaze[0].length;
x = new int[numRows][numCols];
}

这将允许您从该(Maze)类上下文中访问变量。

根据您想要执行的操作,您还可以为字段提供访问器,以允许子类访问它们(使用 protected 来防止包外部的其他类访问它们或 public 如果您希望其他类访问它们)...

public int getNumRows() {
return numRows;
}

看看Understanding Class MembersControlling Access to Members of a Class了解更多详情

关于java - 如何在一种方法和另一种方法中使用声明的变量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28822056/

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