简体   繁体   中英

How to Print a specific point from an array from another method ? #Java

public class NewTest {

    public static void main(String[] args)
    {
        String [][] table;
        table = new String [4][4];
        for(int y=0; y<4; y++){
            for(int x=0; x<4; x++){
                table[y][x] = " ~  " ;
            }   
        }
        int y, x;
        for(y=0; y<4; y++)
        {   
           System.out.print(y+": ");
           for(x=0; x<4; x++)
               System.out.print(table[y][x]+" ");
           System.out.println();
        }                   
    }
    public void table ()
    {           
          System.out.println(table[2][2]);
    }
}

//this is the line where I have problems ! System.out.println(table[2][2]);

The problem is that String [][] table is local to the method where it is declared, and is, therefore, invisible to other methods of the class.

There are two ways of making it visible:

  • Make String [][] table a static member in the enclosing class (because main is static ), or
  • Pass String [][] table to the function as a parameter.

The second solution is usually better:

// Here is the declaration of a method taking 2D table
public static void showTableCell(String [][] table) ...
...
// Here is a call of that method from main():
showTableCell(table);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM