How to call a constructor from main method in java? - 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;
}
}

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()).

To call your constructor you must 'construct' a new object.
Eightqueens obj = new Eightqueens(5);

just when you instantiate your object of class with new keyword , you call your constructor.
like this :
public static void main(String[] args) {
Eightqueens eq = new Eightqueens(5);
}

You can start by calling your constructor by making a new instance of Eightqueens
int size = 1; // anything
new Eightqueens(size);

This code does not return null, it does not return anything. You never call your constructor :
public static void main(String[] args) {
Eightqueens eq = new Eightqueens(5);
}

You can't call your constructor again. It only runs at the start of the code.
You can however, create a new instance of it to run it again.

The Dialog Box is empty because the value of board is nothing, which is because it has not been initialized. The board get a value in the constructor method. So you have to call the constructor method before you show the dialog box.
public static void main(String[] args)
{
Eightqueens eq = new Eightqueens(8);
JOptionPane.showMessageDialog(null,board);
}
Also, in the constructor method, you are overwriting the value of size given by you earlier. Thus, there is practically no need to supply the variable to the method. So, either you remove the line:
size = 8;
or, change the constructor method to not input the value, like this:
public Eightqueens ()
{
int 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;
}

Related

Returning Integer Array List from another class returns null pointer exceptions when getting specific value

new to java and need some pointers
I am trying to create an array list in one class then return it and iterate through its values in a separate main class. However when i use the get method to return a specific value in the array it produce a null pointer exception. What am I doing Wrong ?
import java.util.*
public class ReadFile
{
private ArrayList<Integer> height;
public ReadFile()
{
ArrayList<Integer> height = new ArrayList<Integer>();
for(int x = 0; x <= 3; x++)
{
height.add(x);
}
}
public ArrayList<Integer> getHeights()
{
return height;
}
}
Main Class
import java.util.*
public class Jumper
{
private ReadFile readFile;
public Jumper()
{
readFile = new ReadFile();
}
public static void main(String[] arg)
{
Jumper game = new Jumper();
System.out.println(game.readFile.getHeights().get(1));
}
}
You're declaring a field named height:
private ArrayList<Integer> height;
and then you're déclaring a local variable also named height:
public ReadFile()
{
ArrayList<Integer> height = new ArrayList<Integer>();
everything you do with height in the constructor is done on the local variable, and nothing is done on the field.
This line is the problem
ArrayList<Integer> height = new ArrayList<Integer>();
Instead of assigning a value to the height member field, you create a new height variable that only exists inside the constructor.
You should instead do height = new ArrayList<Integer>();, similar to how you do with readFile.
P.S: Having a local variable with the same name as a member field is called "variable shadowing". Depending on what IDE you are using, it might warn you about it, as it's not an uncommon mistake.
Please change this line ArrayList<Integer> height = new ArrayList<Integer>(); to height = new ArrayList<Integer>(); inside the constructor of ReadFile. What happens is both the height references are different.
In this code
public ReadFile() {
ArrayList<Integer> height = new ArrayList<Integer>();
for(int x = 0; x <= 3; x++) {
height.add(x);
}
}
The height is local to the Constructor ReadFile(), so only that is initialized and the private ArrayList<Integer> height; remains null and that's what causes the Exception.

Using static methods

I'm trying to build a matrix with a static method and I return a new constructor with the built matrix, but whenever I try to get the matrix values, it all ends up being empty.
public class KeyTable {
private char[][] key;
final static int rows = 5;
final static int columns = 5;
public KeyTable(char[][] key) {
this.key = key;
}
public static KeyTable buildFromString(String keyPhrase)
{
char[][] alpha = new char[5][5];
char[] alphabet = "abcdefghiklmnopqrstuvwxyz".toCharArray();
int followingAlphabet = 0;
for(int r = 0; r < rows; r++)
{
for(int c = 0; c < columns; c++)
{
if(followingAlphabet <= keyPhrase.length()-1)
alpha[r][c] = keyPhrase.charAt(followingAlphabet);
else
alpha[r][c] = alphabet[followingAlphabet];
followingAlphabet++;
}
}
System.out.println(Arrays.deepToString(alpha));
return new KeyTable(alpha);
}
public char[][] getKeyTable()
{
return this.key;
}
}
Main class:
package com.company;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char[][] alpha = new char[5][5];
KeyTable key = new KeyTable(alpha);
System.out.println(Arrays.deepToString(alpha));
KeyTable.buildFromString("EXAMPLE");
key.getKeyTable();
System.out.println(Arrays.deepToString(alpha));
System.out.println(Arrays.deepToString(key.getKeyTable()));
}
}
It is because you did two separate things. First you created a KeyTable object with your array. Then you ran a bunch of other random stuff (buildfromString method). Then you ask it to return an empty key and print it. I have no clue what you are actually trying to do but it definitely won't print anything because you didn't store it anywhere. You also have it returning an empty object which makes no sense either. Something like this:
key=KeyTable.buildFromString("Example");
You then can return you results in your main application to display the information properly. I hope that this helps you. If you provide more details on what you are actually trying to do, I can help more on that.

How can I pass these parameters (java)?

I am very new to Java, and I'm having a difficult time figuring out how to take arguments from the command prompt and pass them around in my code. I am able to get them into the main method of my code, but I'd rather have them in the Chessboard class. There is a public static int n that is hard coded, but I would like it to be whatever I send in as arguments. I'll later be taking an initial position for a queen's placement, so I'm hoping the process will be similar; if I get help with this, hopefully I can use the same technique for that.
public class Chessboard {
public static void main(String[] args) {
System.out.println("Hello World");
Chessboard board = new Chessboard(); //creates a Chessboard object
board.start();
}
public static int n = 8;
private static int board[][]; //this is the Chessboard array
private int numQueens; //this is the number of queens on the board
public Chessboard(){
numQueens = 0; //initialized to zero, no queens on board to start yet
board = new int[n][n]; //nxn 2D array of zeros
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
board[j][k] = 0; //redundant, but I need to learn how to
} //initialize. this manually puts zeros into
} //the array
}
...and the code continues from here, but I don't think it's necessary. If it is, I'm happy to upload it.
Thank you for your time.
Here's what I'd do.
public static void main(String[] args) {
try {
int firstArg = Integer.parseInt(args[0]);
Chessboard board = new Chessboard(firstArg);
// Do some stuff with the chessboard here.
}
catch(NumberFormatException e) {
System.out.println("That's not a number");
}
}
This looks at the first command line argument and tries to convert it to an int. If it succeeds, it passes that int to the constructor of Chessboard to make an object for you to use.
This snippet also shows how you can provide code that runs if the first command line argument isn't actually a number.
Notice that the main method is already in your Chessboard class. If you want to leave your n variable as static, you can just do this in the main method.
n = Integer.parseInt(args[0]);
If you make n an instance variable instead of having it be static, then the answer that David Wallace gave will point you in the right direction.
In your Chessboard Class create an
private String[] args;
Then add an setter to Chessboard like:
public void setArgs(String[] args{
this.args = args;
}
Then put something like this in your main:
public static void main(String[] args) {
Chessboard board = new Chessboard();
board.setArgs(args);
board.start();
}

JUnit: test builder with private field

I'm a beginner and I have a problem with JUnit test in the constructor of a class.
The class that I want to test is called IntSortedArray and is as follows:
public class IntSortedArray {
private int[] elements;
private int size;
public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}
public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}
public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}
//other code...
}
With Eclipse I created a class for JUnit:
public class IntSortedArrayUnitTest {
private IntSortedArray isa;
#Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}
}
I started to write a test class with the intention to test all the methods of the class IntSortedArray, including constructors.
The first method testConstructorArray16Elements() wants to test the first builder.
So I thought I would check if the creation of the array elements is done properly, so the for loop counts how long elements and make sure it along 16 (as required).
But Eclipse generates (rightly) a mistake because elements is private.
How can I fix this error? I don't want to put the public field and if possible I would like to avoid creating a method public int[] getElements().
What do you recommend?
Another question: I can do two assert the same method? One to test the length of the array and the other to test that size is 0.
I hope not to have made big mistakes, this is the first time I use JUnit.
PS: how can I test the second constructor?
Thank you very much!
It looks like your class fields are declare as private but you trying to access then from outside the class. You need to provide the accessors methods in you class to make them visible:
private int[] elements;
private int size;
public static final int MAX = 16;
public int[] getElements() { ... }
public int getSize() { return size; }
Then you will be able to write below code:
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.getElements()) {
expected += 1;
}
assertEquals(expected, IntSortedArray.MAX );
It looks like your constructor has created an array for 16 integers, but does not initialize it with any value. To do that you should have below code:
public IntSortedArray() {
this.elements = new int[MAX];
this.size = 0;
for (int i=0 ; i < MAX ;i++) {
elements[i] = i;
size++;
}
}
You'll have to write a getter method for your array, or implement an Iterator

How to pass an 2D array to jtable in Netbeans

It is my first time I create a jtable,I want to display a jtable of int from another class.So I call the method getTable and assign it to the jtable,is it right?
jTable1 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new int[][] = TableAdapter.getTableC()
));
jScrollPane1.setViewportView(jTable1);
It keeps saying arraydimension missing, then I call the method getDimension() and I inserted it in various ways
new int[getDimension()][] = TableAdapter.getTableC()
or
new int[getDimension()][new int[getDimension()][] = TableAdapter.getTableC()
Thanks in adavance, and I am using Netbeans.
I get the an animal table which has two types of animals and from this I interpret to integer code which is stored in a new table(tableC) just to make it easier
package tigers.bunnies;
public class TableAdapter {
static public int tableC[][];//=new int[3][3];
static private int dimension;
public void Table(){
Animal tableT[][];
tableT = table.getTable();
dimension=tableT.length;
//int tableC[][];
tableC = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
if(tableT[i][j]==null){
tableC[i][j]=0000;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0001;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0002;
}
}
}
}
public static int[][] getTableC() {
return tableC;
}
public static int getDimension() {
return dimension;
}
}
also when I use
jTable1.setModel(new javax.swing.table.DefaultTableModel(
TableAdapter.getTableC()
));
it has these errors:
(C:\Users\user\Desktop\error.png)
Your getTableC method is static but your Table method, which initializes the array, is not, resulting in returning an uninitialized array. make Table method static or remove static keyword from getTableC, tableC and dimmension and make Table method a constructor.
package tigers.bunnies;
public class TableAdapter {
public int tableC[][];//=new int[3][3];
private int dimension;
public TableAdapter(){
Animal tableT[][];
tableT = table.getTable();
dimension=tableT.length;
//int tableC[][];
tableC = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
if(tableT[i][j]==null){
tableC[i][j]=0000;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0001;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0002;
}
}
}
}
public int[][] getTableC() {
return tableC;
}
public int getDimension() {
return dimension;
}
Also, an int array is not an Object array. Change it to Integer before passing to JTable model:
TableAdapter ta = new TableAdapter();
int[][] temp = ta.getTableC();
Integer[][] Result = new Integer[temp.length][temp[0].length];
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++)
result[i][j] = new Integer(temp[i][j]);
}
Object[] header = {"Column1", "Column2"};
jTable1.setModel(new javax.swing.table.
DefaultTableModel(result, header)
Probably your TableAdapter.getTable() method returns an array of single dimension. Also you didn't supply the table header but I don't think it's the direct cause of the exception. You should call setModel this way:
Object[] header = {"Column1", "Column2..."};
jTable1.setModel(new javax.swing.table.
DefaultTableModel(TableAdapter.getTableC(), header)

Categories

Resources