2

我只是发布伪代码,希望您能理解:

导入 java.util*.;

主要方法{

子方法1();

submethod1() {

 Screen input = new Scanner(System.in);
 int buy = input.nextInt();

  if( buy != 0) {
     submethod2();
    }

 submethod2() {
 Screen input = new Scanner(System.in);
 int[][]grid = new int [5][6]
 int row = input.nextInt();
 int col = input.nextint();
 grid[row][col] = 1;

假设我为 row 输入了 1,这次为 col 输入了 1。然后grid[1][1] = 1。我想保存 的值,grid[1][1]以便下次输入第 2 行第 2 列时,我将拥有:

 grid[1][1] = 1;
 grid[2][2] = 1; and so on for whatever row-col combination I type.

最后我想回到 submethod1,我想让 submethod1 理解 grid[1][1] = 1 并且 grid[2][2] 也有值 1;等等....

4

3 回答 3

0

Below I am assuming that you are asking about saving value of grid in an instance of program and not between various instances of program calls. if you want to save value of grid between varrious program calls than you will have to store value of grid in some file etc.

instead of creating the array grid inside submethod2(), create it as a class variable and submethod1(), submethod2() as member functions.

create an object in main method and call submethod1() on the object

something like

class ABC
{
int[][] grid = new int[5][6];

 submethod1()
{
...
}

 submethod2()
{
 ...
 }


public static void main(String args[])
{
  ABC abc = new ABC();
  abc.submethod1();
}

}
于 2012-09-26T11:31:37.947 回答
0

处理此类问题的最佳方法是使用面向对象的方法。请记住,这就是我们使用 Java 的原因。

创建一个GridItem具有三个属性row, column,的类value。当您存储一些值时,创建对象GridItem并将其存储在全局列表中。然后,您可以在任何函数中对其进行迭代并访问存储了哪些值。

     class GridItem
    {
        int row;
        int column;
        int value;

        public GridItem(int row, int column, int value)
        {
            this.row = row;
            this.column = column;
            this.value = value;
        }
        //Provide getters only
    }
    ArrayList<GridItem>items = new ArrayList<GridItem>();
    items.add(new GridItem(1, 1, 1));// 1 row 1 col 1 value
    items.add(new GridItem(2, 2, 2));// 2 row 2 col 2 value


    items.get(0).getRow()// get first 

还有其他几种解决方案。例如,维护一个全局数组,然后扩展它。创建网格列表等,但它们都很复杂并且做得比必要的多。

于 2012-09-26T11:45:57.237 回答
0

这是一个范围界定问题。本质上,您每次调用时都会创建一个新int[][]变量。要么将其存储为类变量,要么将其传入然后从中返回并自己手动更新(我不推荐这种方法)gridsubmethod2()submethod2()

如果没有更多上下文,很难推荐如何将问题分解为objects,但一种解决方案可能如下所示:

import java.util*.;

public class MainClass {
    private int[][] grid;

    public static void main(String[] args) {
        submethod1();
    }

    private void submethod1() {
        grid = new int[5][6];
        Screen input = new Scanner(System.in);
        int buy = input.nextInt();

        if( buy != 0) {
            submethod2();
        }
    }

    private void submethod2() {
        Screen input = new Scanner(System.in);
        int row = input.nextInt();
        int col = input.nextint();
        grid[row][col] = 1;
    }
}
于 2012-09-26T11:25:42.027 回答