Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a constructor from main method in java?

Tags:

java

I need to write a program to solve the eight queens problem and I have no idea how to do it, but I have already started with the multidimensional array. The thing is that I don't know how to call a constructor from the main class, just to check if the array was constructed properly, or how to call it from a method. Can anybody help, please? This is the code, it returns null.

import javax.swing.JOptionPane;


public class Eightqueens

{
    private static int[][] board;

    public static void main(String[] args) 
    {
        JOptionPane.showMessageDialog(null,board);
    }

    public Eightqueens (int size)
    {
        size = 8;
        board = new int[size][size];

        int row;
        int col;

        for (row = 0; row < size; row++)
            for (col = 0; col < size; col++)
                board[row][col] = 0;
    }

}
like image 889
Paw Avatar asked Mar 28 '26 21:03

Paw


2 Answers

You are supposed to use the value passed to the constructor, not overwrite it :

...
private int[][] board;
...
public Eightqueens (int size)
{
    size = 8; // remove this
    ...
}

public int[][] getBoard() 
{
    return board;
}

public static void main(String[] args) 
{
    Eightqueens equeens = new Eightqueens (8); // create an instance
    JOptionPane.showMessageDialog(null,equeens.getBoard()); // use accessor to get
                                                            // board
}

In addition, it doesn't make sense to initialize a static variable (board) in the constructor, since each new instance you create would overwrite its value. I'd change it to non-static, and then you can get it from your instance by using an accessor method (equeens.getBoard()).

like image 63
Eran Avatar answered Apr 01 '26 08:04

Eran


To call your constructor you must 'construct' a new object.

Eightqueens obj = new Eightqueens(5);
like image 37
Kevin DiTraglia Avatar answered Apr 01 '26 09:04

Kevin DiTraglia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!