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

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.

Related

Counting Sort issue

public static void countingSort(Integer[] a, int n) {
//TODO
//COMPLETE THIS METHOD
int[] counter = new int[n+1];
int[] sorted = new int[a.length];
Arrays.fill(counter,0);
// fills counter array with each number count
for ( int i = 0 ; i < a.length; i++){
counter[a[i]] += 1;
} // adds n-1 index + n index
for (int i = 1; i < counter.length; i++) {
counter[i] = (counter[i] + counter[i-1]);
} // shifts array to the right
for (int i = counter.length-1; i > 0; i--) {
counter[i] = counter[i-1];
} // fills sorted array with the sorted out counts
for (int i = 0; i < a.length; i++ ){
sorted[counter[a[i]]] = a[i];
counter[a[i]]++;
}
}
When ran it throws an array out of bound exception in the body of the first for loop. Im having trouble seeing it, if anyone could help guide me, it'd be much appreciated.
When ran it throws an array out of bound exception in the body of the
first for loop.
That would be this:
for ( int i = 0 ; i < a.length; i++){
counter[a[i]] += 1;
}
Im having trouble seeing it, if anyone could help
guide me, it'd be much appreciated.
An ArrayIndexOutOfBoundsException in that loop can only mean that you are exceeding the bounds of a or those of counter. It is clear from inspection that you are not exceeding the bounds of a (though you could both eliminate that possibility and make the code a bit cleaner by switching to an enhanced for loop). The only remaining possibility is that you are exceeding the bounds of counter.
The approach you've implemented supports only non-negative integers in the input array, and requires the method invoker to pass an upper bound on the element values as the second parameter. If those constraints are not satisfied then an exception such as you observe will be thrown.
That is, if the exception is thrown where you say it is, then the problem is with the input.

Over writing an array vs. Deleting and re-initializing it? Java

is overwriting an array in java the same as deleting the elements and inserting new ones? I have a 50x50 array that stores floating point values. A method calculates new values and sends them to the same array that already has these values for overwriting the previous ones. This is a recurring procedure. After around 1500 iterations, stackoverflow error occurs. Would it be different if I set the array to null first before writing values to it?
The code is:
float n = input.nextFloat();
public static void calculate_initial_float_values(){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a.length; j++){
a[i][j] = i+j+n*n ;
}
}
change_values();
}
public static void change_values(){
n = rng.Random(9);
calculate_initial_float_values();
}

Changing index positions within an array [duplicate]

This question already has answers here:
Java method to swap primitives
(8 answers)
Closed 4 years ago.
I have a question regarding a 1d array and what I am attempting to do with this array is changing the index value of any value within the array for example
int[] num = new[2,4,6,9]
and what I want to do with this array I want position 0 to become position 1 and position 1 to become 0. So the array would look like [4,2,6,9] and that part is easy enough to do but I am struggling with the parts that come after which is I would like for the array to continue down this path so [4,6,2,9]->[4,6,9,2] and I am struggling with that. So far I am using two array to try this but I am having difficulties. Also I am attempting to do this with all spots and not just the first one.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
temp[j] = temp2[i];
if (j != 0) {
temp[j - 1] = temp2[j];
}
}
revert(); //I use this methods to restore any changes made so I can attempt with the next spot
}
Keep only 1 for loop and 1 temp variable to swap your tab.
for (int i = 0; i < N; i++) {
tmp = tab[i];
tab[i] = tab[i + 1];
tab[i + 1] = tmp;
}

Character array, can't get array length

This is in Java
I'm not sure what is wrong with the arrayName.length in my code, it doesn't work on both occasions
for (int i = 0; i<arr.length; i++)
{
for(int j = 0; j < arr2.length; j++)
{
}
}
These two arrays are char arrays and does not seem want to work with the .length method. It says that "length cannot be resolved or is not a field"
Can someone please explain to me why this is happening
You aren't using arrays in your code, you are using ArrayLists. They are totally different and have different methods. The equivalent method to length for ArrayList is .size().

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.

Categories

Resources