OutOfBounds when working with objects in an array - java

When I am creating an array of Example objects, I call something like initializeArray(); I use a simple nested for loop to traverse through the array and then assign new objects with values to each index of the array using exampleArr[i][j] = new Example(false, false, false, 0); however, calling this gives me an java.lang.ArrayIndexOutofBoundsException:0 at the line above.
I am assuming that I am instantiating the new object incorrectly, as this also happens in another method which is supposed to display all of the Example objects in the array. However, I will post the nested loop I am using in case there is something that i've done wrong that I can't see.
public void initializeArray(){
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getColumns(); j++){
tileArr[i][j] = new Tile(false, false, false, 0);
}
}
}
//Declaration of rows and columns
private int rows;
private int columns;
Tile[][] tileArr = new Tile[rows][columns];
public void setRows(int r)
{
rows = r;
}
public void setColumns(int c)
{
//various setters and getters for the array
columns = c;
}
public int getRows()
{
System.out.print(rows);
return rows;
}
public int getColumns()
{
System.out.print(columns);
return columns;
}
Thanks everyone for your help! The problem has been solved.

Declare your tileArr at the top but do not initialize.
Tile[][] tileArr;
Then initialize your array before your for loop in the initializeArray() (This is assuming your rows and columns is set. You can add logic to check this as well).
tileArr = new Tile[getRows()][getColumns()];
tileArr = new Tile[rows][columns]; //Do this instead if you don't want the print statements to be called

As #gonzo said you have got to initialize your array to allocate enough memory for all the positions you are going to be using.
Tile[][] tileArr;
public void initializeArray(){
Tile[][] tileArr = new Tile[getRows()][getColumns()];
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getColumns(); j++){
tileArr[i][j] = new Tile(false, false, false, 0);
}
}
return titleArr;
}
//...wherever you want it
this.tileArray = this.initializeArray()
But there are cases when you don't know how big this array may be. For those cases you should be using List<Tile> type like LinkedList<Tile> or ArrayList<Tile> so that you don't need to allocate space for every new position to use.

Related

fastest way to shuffle matrix row

I need to shuffle the rows of a matrix, creating a new randomized matrix with all the same properties of the original one. Is there any approach faster/more efficient than the one I am adopting now?
private static SparseDoubleMatrix2D shuffleMatrix(SparseDoubleMatrix2D aMatrix, int[] ordering, int size) {
SparseDoubleMatrix2D result = new SparseDoubleMatrix2D(size, size);
for (int i = 0; i < size; i++) {
int row = ordering[i];
for (int col = 0; col < size; col++) {
result.set(i, col, aMatrix.get(row, col));
}
}
return result;
}
each time the method is called, a new ordering is given according to this other method:
private static void shuffleArray(int[] ordering, MersenneTwisterFast r) {
for (int i = ordering.length - 1; i > 0; i--) {
int index = r.nextInt(i + 1);
int a = ordering[index];
ordering[index] = ordering[i];
ordering[i] = a;
}
}
It depends on the implementation of SparseDoubleMatrix2D. Presently you are shuffling the rows by re-assigning every element in the matrix, however, since only rows are being shuffled and not columns, you should be able to shuffle it by reassigning the references to each row only, which should cut down the processing time from O(size*size) to O(size).
To answer the OP's comment about deep copy, a good implementation of SparseDoubleMatrix2D would be something like this:
class Matrix2D {
private int[] ordering;
private MatrixRow[] rows;
public double getValue(int row, int col) {
return rows[ordering[row]].get(col);
}
...
}
Ordering starts off looking like {0, 1, 2, ... n-1}. When you need to randomize, just set a new ordering array. That way, the original order which
is the order of rows[] never gets changed.

Creating a method of type class Matrix to add two matrices

so, I'm supposed to make a matrix using HashMap<Integer,ArrayList<Number>>, where Number is a class who's instance variables are numerator and denominator.
Class Matrix inherits Class Number, which have methods like fillMatrix(), printMatrix(), addMatrix(Matrix,Matrix) and subMatrix(Matrix,Matrix), problem is in those last two methods, i made them but I'm pretty sure they are completely wrong since i get a NullPointerxception, How do i make such methods?
here is the code.
public class Matrix extends Number implements Calculation
{
public static int rows;
public static int cols;
private ArrayList<Number> myArray;
private ArrayList<Double> myArray2;
private ArrayList<Double> myArray3;
private ArrayList<Double> myArray4;
private HashMap <Integer, ArrayList<Number>> hm;
private HashMap <Integer, ArrayList<Double>> hm2;
public Matrix(int r, int c)
{
hm = new HashMap<>();
hm2 = new HashMap<>();
rows = r;
cols = c;
}
public void fillMatrix()
{
Scanner input = new Scanner(System.in);
myArray = new ArrayList<>();
myArray2 = new ArrayList<>();
System.out.println("Enter the number of rows");
rows = input.nextInt();
System.out.println("Enter the number of columns");
cols = input.nextInt();
Number n = new Number();
for (int i = 0; i < cols;i++)
{
n.setNumerator(i);
n.setDenominator(i+1);
myArray.add(new Number(i,i+1));
double xn = n.getNumerator();
double xd = n.getDenominator();
myArray2.add(xn/xd);
}
for (int i = 0; i < rows; i++)
hm2.put(rows,myArray2);
}
public void printMatrix()
{
for (int i = 0; i < rows; i++)
{hm.put(rows,myArray);
System.out.println(myArray3.toString());
}
}
public Number getItem(int rowNO,int colNO)
{
rows = rowNO - 1;
cols = colNO - 1;
hm.get(rows);
return myArray.get(cols);
}
public void addMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sum = a1+a2;
myArray3 = new ArrayList<>();
myArray3.add(sum);
}
x1=a;
x2=b;
}
}
public void subMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
{ x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sub = a1-a2;
myArray4 = new ArrayList<>();
myArray4.add(sub);
}
x1=a;
x2=b;
}
}
}
}
I'm a bit confused here, so I'll point out some things I noticed.
First off it's difficult to understand your code because of the variable names.
Also none of the methods are static, so i don't really understand why you're bringing in two Matrices for the calculation, then setting them equal to the first two you create in the beggining of both methods.
Next, you have two brackets after your for loop in the subtraction method, I'm guessing it was just a typo when pasting in StackOverflow.
The myArray objects you're adding the sum too is not going to be accumulating all the sums because you are creating a new arraylist each time that loop goes through. Create it outside the loop.
The NullPointerException could be anywhere really, it's hard to tell because the code is a bit confusing.
I would recommend using the LWJGL library which has has classes like Matrix4fand methods like Matrix4f.add();which will help you accomplish this.
Try running your program in debug mode so you can understand which statement gives you null pointer exception.
And I've noticed you have your rows and columns as static but you can change change them within constructor. It seems there is a logical mistake there. These two may be the cause of your exception if you didn't ever give initial value of them before.
If your matrixes can have different rows and columns then you definitely shouldn't use static for them.
To actually understand where nullpointerexception is given, you should also write your main code. But like I said, in debug mode, you can also see it yourself.

ArrayList giving problems in java. positive integers solution to x+y+z+w = 13

So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.

Nested Loop with program, boolean arrays?

In the constructor of the model class, I need to allocate the memory of this array of booleans (boolean[ ][ ] is_hidden;). I also need to set them to true, but have no idea how this happens, a nested loop will have to be used like the one in the paint method at he bottom, in order to set each element.
class MineFinderModel {
public static int MINE_SQUARE = 10;
public static int EMPTY_SQUARE = 0;
int num_of_cols;
int num_of_rows;
int[][] the_minefield;
boolean[][] is_hidden;
public MineFinderModel(int n_cols, int n_rows) {
num_of_rows = n_rows;
num_of_cols = n_cols;
the_minefield = new int[num_of_cols][num_of_rows];
is_hidden = new boolean[][];
}
Paint method example:
for (int i = 0;i<numCols;i++)
{
for(int j = 0;j<numRows;j++)
{
Rectangle r = getRect(i,j);
g.setColor(Color.black);
g2.draw(r);
if(i==0&&j==0) {
g2.drawOval(x,y,w,h);
g2.fillOval(x,y,w,h);
}
if(i==0&&j==(numRows-1))
g2.fillOval(x,y,w,h);
if(i==(numCols-1)&&j==0)
g2.fillOval(x,y,w,h);
if(i==(numCols-1)&&j==(numRows-1))
g2.fillOval(x,y,w,h);
You need to define the array with the sizes e.g.
is_hidden = new boolean[cols][rows]();
and iterate through, setting each cell to true (booleans, and boolean arrays, default to false).
Note that Arrays.fill() exists, but will only get you halfway, since it won't fill multidimensional arrays. You can use this, but you'd have to iterate through the rows, and use Arrays.fill on each row. Perhaps not worthwhile in this example, but worth being aware of regardless.
Try this:
int num_of_cols = 2;
int num_of_rows = 3;
boolean[][] is_hidden;
is_hidden = new boolean [num_of_cols][num_of_rows];
for (int i = 0; i < num_of_cols; i++) {
for (int j = 0; j < num_of_rows; j++) {
is_hidden[i][j] = true;
}
}
You can see it is now correctly initialized:
for (boolean[] col : is_hidden) {
for (boolean elem : col) {
System.out.println(elem);
}
}
when you define a boolean array the value of all the elements are false by default.
I would suggest instead of looping through all the elements, implement your conditions in way that you can use the default false value.
Eg.
boolean[][] isEnabled = new boolean[10][10];
// code to set all elements to true
if(isEnabled[i][j]){
//some code
}
this can be easily replaced by
boolean[][] isDisabled = new boolean[10][10];
if(! isDisabled[i][j]){
//some code
}
You can save processing time this way and code looks neat :).
Simply write a nested loop.
for (int i = 0;i<n_rows;i++){
for(int j = 0;j<n_cols;j++){
is_hidden[n_rows][n_cols] = true;
}
}
I have a simple solution for you: instead of using your array is_hidden and fill each element of it with true, use the name isVisible and don't fill it at all since every element of it is already initialized to false ;)

Java: Accessing pointers

I get: 'unexpected type
required: variable
found : value' on the marked lines (*)
for (int i = 0; i < boardSize; i++) {
for (int j = 0; j < boardSize; j++) {
rows[i].getSquare(j) = matrix[i][j]; // * points to the ( in (j)
columns[j].getSquare(i) = matrix[i][j]; // * points to the ( in
int[] b = getBox(i, j);
int[] boxCord = getBoxCoordinates(i + 1, j + 1);
boxes[b[0]][b[1]].getSquare(boxCord[0], boxCord[1]);
}
}
This is my Row class:
private Square[] row;
Row(int rowCount) {
this.row = new Square[rowCount];
}
public Square getSquare(int index) {
return this.row[index];
}
Please help me out by pointing out what I'm doing wrong here.
Thanks in advance.
You cannot assign something to the return value of a method. Instead, you need to add a setSquare() method to the Row class:
public Square setSquare(int index, Square value) {
this.row[index] = value;
}
and use it like this:
rows[i].setSquare(j, matrix[i][j]);
Java doesn't have pointers - references are not the same thing.
It's impossible to tell what's really going on based on the code you posted. I think you need a method to set the value of that Square in the private array your Row class owns.
public void setSquare(int index, Square newSquare) {
this.row[index] = newSquare;
}
It looks like a poor abstraction, in any case.
Java has no pointers. Objects are passed and returned by reference. In terms of C++, rows[i].getSquare(j) is an rvalue, not an lvalue, so you cannot assign to it.
Instead, you should create and use rows[i].setSquare(...).

Categories