Reputation: 1
I am pretty new to java but i have to initialize an 2d-array size n, in this example 10. After initialization i want to check the diagonal entries if they are false, and if set them to true. After i want to return value of i.
This is what i coded:
First of all initialization of the array:
public static void init(int n) {
boolean friendship[][] = new boolean[n][n];}
and after i tried this:
public static int addUser(String name) {
int id=0;
for ( int i=0;i<friendship.length;i++) {
if ( friendship[i][i] = false) {
friendship[i][i] = true;
id = i;
}
}
return id;
}
Sadly its throwing:
Exception in thread "main" java.lang.NullPointerException
at x.SocialNetwork.addUser(SocialNetwork.java:18)
at x.SocialNetwork.main(SocialNetwork.java:53)
What can i do to fix this?
PS: Sorry for bad english and formatting.
Upvotes: 0
Views: 69
Reputation: 279880
I assume you have a static
field called friendship
. In this method
public static void init(int n) {
boolean friendship[][] = new boolean[n][n];
}
you are declaring a new local friendship
variable, that is shadowing the static
member. Therefore, the static
friendship
field remains null
and when you try to access it in addUser
you get a NullPointerException
.
Use
public static void init(int n) {
friendship = new boolean[n][n];
}
assuming again that you have something like
public static boolean[][] friendship;
In this
if ( friendship[i][i] = false) {
you are actually setting friendship[i][i]
to false
. The equality operator is ==
.
This is how I see your class
public class Test {
/* visibility identifier doesn't matter */ static boolean[][] friendship;
public static void init(int n) {
// this is a different variable from the member declared above
// it is a local variable
boolean friendship[][] = new boolean[n][n];
}
public static int addUser(String username) {
int id=0;
for ( int i=0;i<friendship.length;i++) {
if ( friendship[i][i] = false) { // referring to static field, not the local variable in init()
friendship[i][i] = true;
id = i;
}
}
return id;
}
}
Upvotes: 3