user3212719
user3212719

Reputation: 139

2d array values aren't access in main method

How to access values stored in 2d array puzzle[][] in main class. i am not able print these values in generate() but not in main method.

import java.util.Random;

public class generator {

 static   int  puzzle[][] = new int[9][9];

 public int[][] generate() {
     return puzzle;
 }

 public static void main(String args[]){
    generator g = new generator ();
    g.generate();   
 }  
}

Upvotes: 1

Views: 158

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 209012

"How to access values stored in 2d array puzzle[][] in main class"

My guess is you're having problems iterating through the array. Without giving you the answer, I will give you some things to think about and look at to help you in your learning.

  • You need to iterate (loop) through the array. This is not like a regular array, where you can use one loop. Since it is a 2D array, you will need two loops. Take a look at Iterating through MultiDimensional Arrays
  • For methods, you need to determine if you want the method to do the printing, or if you want the method to return something. If you want the method generate() to print, then the return type should be void and you need to add some System.out.println()s in a loop. The above link can show you how to iterate the array. If you did it this way, then calling g.generate() will work.
  • Since you currently have the method generate() returning an array, then you need to do something like this

    int[][] array = g.generate();
    

    Then you need to iterate through it.


Read more on Defining methods and Loops

Upvotes: 0

Tanmay Patil
Tanmay Patil

Reputation: 7057

As far as I get from your question, you need the following to be put in the main method.

int[][] localPuzzle = g.generate();

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.println(localPuzzle[i][j]);
    }
}

OR directly using generator.puzzle[i][j] should work too.

Hope this helps. Please clarify if you want something else.

Upvotes: 1

Related Questions