【问题标题】:How to use object from main method in another method如何在另一个方法中使用主方法中的对象
【发布时间】:2018-10-19 18:50:16
【问题描述】:

我正在尝试在我的项目的compareGrids 方法中使用RandomGrid rGrid,但是我似乎不知道该怎么做。我最初在 main 方法之外有 RandomGrid 构造函数,但是每当我尝试运行它时都会出现堆栈溢出错误。我有另一个与这个非常相似的类,在 main 方法之外有一个 ButtonGrid 构造函数,它工作正常。感谢您的帮助!

public static void main(String[] args) {
    new ButtonGrid(WIDTH, LENGTH);
    RandomGrid rGrid = new RandomGrid(WIDTH, LENGTH);

}
public int compareGrids() {
    String[] args = {};
    ButtonGrid.main(args);

    int numCorrect = 0;
    for (int i = 0; i < WIDTH; i++) {
        for (int j = 0; j < LENGTH; j++) {
         if (grid[i][j].getBackground() == ButtonGrid.main(rGrid).grid[i][j].getBackground()) {
                numCorrect++;
            }
        }
    }
    System.out.println(numCorrect);
    return numCorrect;
} 

【问题讨论】:

  • 将您的rGrid 传递给compareGrids 或将其设为静态
  • 通过是什么意思?

标签: java class methods main


【解决方案1】:

简单的答案: 将 compareGrids() 设为静态并添加参数

public static int compareGrids(Grid grid1, Grid grid2) {
 ...
}

这是一个入门级的问题,你可能想参考一个简单的java教程来了解基本的类元素和修饰符

【讨论】:

    【解决方案2】:

    要在 compareGrids 中使用 rGrid,它必须是类级别的变量。 宣布 RandomGrid rGrid = new RandomGrid(WIDTH, LENGTH); 外主要。 它应该可以解决您的问题。 目前 rgrid 的范围在 main 方法完成后立即结束

    请粘贴您提到的堆栈溢出错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多