2D Stack implementation, getting NullPointerException - java

I try to implement a 2D Stack like this
private Stack<Char>[][] objectGrid = (Stack<Char>[][]) new Stack[width][height]
However, when I try to push an element to my stack, I keep getting NullPointerException
(objectGrid[x][y]).push(ch)
I checked the debugger, and figured that objectGrid[x][y] appears as null, so I can't do push on it. Is the above initialization wrong, should I do a for loop to initialize the second dimension of my stack array?

Add initialize loop to your code, like this:
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
objectGrid[i][j] = new Stack<Char>();
}
}

Related

Error with adding element to list - repeating n-time last element

Could anyone help me and point out what is wrong here? All the fields are non-static. Function shuffle returns each time different array.
List<Point[]> someArray = new ArrayList<Point[]>();
for(int i = 0; i < 4; i++) {
Point[] temporary = new Point[50];
temporary = shuffle(pointsArray.getPoints());
someArray.add(temporary);
print(someArray.get(i));
}
The result of print in the first loop is ok since they're different. Right after getting out of the loop, I want to print elements of list someArray again.
for(int i = 0; i < 4; i++) {
print(someArray.get(i));
}
The result here is 4 time of the last element.

NullPointer exception being thrown using .equals on string in java? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a 2d array of "#" and "." I am Passing into a method, I am then trying to iterate through the array and find how many "#" are in it. I keep getting a NULLPOINTER exception when using .equals. the method should return the amount of "#" in the array. I tried iterating through the 2d Array and then converted the 2d into a single dimension array and still am getting the EXCEPTION Im not sure what I am doing wrong, any help would be greatly appreciated.
my code is:
public static int countSeats(String[][] aud){
int openSeats = 0;
String [] audit;
audit = new String[120];
int k = 0;
for(int i= 0; i < aud.length; i++)
for(int j = 0; j < aud[i].length; j++)
audit[k++] = aud[i][j];
for(int i= 0; i <= audit.length; i++){
openSeats = audit[i].equals("#")? +1:+0;
}
return openSeats;
You're getting an exception because of your loop condition:
for(int i= 0; i <= audit.length; i++){
Notice how you're using <= and not <. You're looping through the entire audit array, and then going one more than you should, resulting in the NullPointerException.
The fact that you declare String[] audit, makes the solution even more complicated as you MAYBE TRY TO PUT ALL THE 2-D in 1-D thinking that it will simplify the problem for you, but it wont. Stay inside the 2-D, and do the search
int openSeats = 0;
for(int i= 0; i < aud.length; i++)
{
for(int j = 0; j < aud[i].length; j++)
{
if( aud[i][j].equals("#") )
{
openSeats++;
}
}
}
return openSeats;
As others have pointed out, you are running your for loop one iteration extra by having i <= audit.length; instead of i < audit.length;. Also, as a good practice, always keep the String literal on the left side of the method call. E.g. instead of aud[i][j].equals("#"), do "#".equals(aud[i][j]) to avoid any possibility of NPE.

Java ArrayIndexOutOfBounds

Currently working on a student project. I want to figure out the highest number and sort it by bubble sort, the number is parsed from a JLabel, but I get this error everytime. Here is a code snippet:
JLabel[] wuerfelsummen = new JLabel[7];
wuerfelsummen[0] = player1_wuerfelsumme;
wuerfelsummen[1] = player2_wuerfelsumme;
wuerfelsummen[2] = player3_wuerfelsumme;
wuerfelsummen[3] = player4_wuerfelsumme;
wuerfelsummen[4] = player5_wuerfelsumme;
wuerfelsummen[5] = player6_wuerfelsumme;
public int ermittleGewinner(JLabel[] w)
{
int temp;
int[] zahlen = new int[w.length];
for(int i=0; i<=zahlen.length; i++)
{
if(w[i].getText() == null)
{
zahlen[i] = 99999999;
}
else
{
zahlen[i] = Integer.parseInt(w[i].getText());
}
}
for(int i=1; i<zahlen.length; i++)
{
for(int j=0; j<zahlen.length-i; j++)
{
if(zahlen[j]>zahlen[j+1])
{
temp=zahlen[j];
zahlen[j]=zahlen[j+1];
zahlen[j+1]=temp;
}
}
}
for(int i=0; i<=zahlen.length; i++)
This is incorrect, as arrays are 0-indexed, meaning they reach from 0 to length-1.
Change it to
for(int i=0; i<zahlen.length; i++)
Interestingly enough, your other loops avoid this pitfall, although you will still have to be careful about the j+1 later on. Make sure that this can never be >= zahlen.length.
You could simply initialize j with 1 instead of 0 and then replace all occurences of j with j-1 and j+1 with j
change "i<=zahlen.length" in your for loop to "i < zahlen.length".
remember arrays are 0 indexed so you are trying to access an element one index outside of how large your array is with the "<=" method you are currently using
The second loop should start at i=0 instead of i=1. By using i=1, you are again going to try to access one element past the size of your array
ArrayIndexOutOfBounds expcetion comes when code tried to access an element of an array which is not present. In your code, since you are FOR looping one extra time for(int i=0; i<=zahlen.length; i++), you are getting this exception. Keep FOR loop as for(int i=0; i<zahlen.length; i++)
You have not to just check for zahlen[i] but also for w[i] because you are looping on length of zahlen and it may so happen that w is of lesser length then zahlen.

2d Arraydeque insertion

I am using arraydeque to store another arraydeque of type Integer.
My code looks like this:
private ArrayDeque<ArrayDeque<Integer> > grid;
public void initiateGrid(){
for (int i = 0; i < Length; i++)
{
ArrayDeque<Integer> columns = new ArrayDeque<Integer>();
for (int j = 0; j < Width; j++)
columns.add((int)(Math.random() * 100));
grid.add(columns);
}
}
When I try to run this it gives me a NullPointerException on grid.add(columns).
does anyone know what am I doing wrong?
Also if there is a better way to do this, please let me know.
Thanks
initialize grid, because you cannot use a null object, otherwise you get NullPointerException
public void initiateGrid(){
grid = new ArrayDeque<ArrayDeque<Integer>>();
//...
}

Global Java array setting values to 0

I've a slight problem. I'm taking every element in a sparse matrix and putting it into a 1d array named 'b[]'. For example:
00070
00400
02000
00050
10000
Becomes: 0007000400020000005010000
The code below works in that at a given point within the inner-most loop b[] has the correct value as shown below. My problem is that outside of the inner-most loop b[] has a value of:
b[] = 0000000000000000000000000
I cannot understand what I'm missing. It should also be noted that b[] is globally defined, and instantiated within the constructor of this class. The problem is that I'm trying to use this 1d array in another function, and every element within the array is set to 0.
public void return1dSequence() {
// Create paired objects (Pair class).
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
this.b[i] = a[i][j];
// System.out.print(b[i]);
if (this.b[i] == 0) {
pos += 1;
} else {
value = this.b[i];
ml.add(new Pair(pos, value));
pos += 1;
}
}
}
}
Thanks in advance for any replies,
Andre.
You're filling in b[i] for indexes i of your outer loop...
Each time in the inner loop, you overwrite b[i] with value a[i][j].
Last value of a[i] array is always zero.
That's why your b array is zero.
What you want is probably:
int counter = 0;
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
b[counter] = a[i][j];
counter++;
}
}
The first thing i want to mention is that u shouldn't declare your variables (a, b....) static. Maybe u got hit by a mean side effect after creating two instances of Sparse. Try to define them as non static and report if it still wont work.
Best regards
Thomas
Try removing this from each call to b[] if you want to access b[] as static.
Also, are you sure you are not overwritting b[] anywhere else in the code? This is most likely the issue because of the public static declaration. Try making it private and removing static and see if you still have the issue.

Categories

Resources