英文:
Cannot load from byte/boolean array because "BlackWhite.marked" is null
问题
以下是翻译好的代码部分:
当我运行下面的代码时,尽管我不知道原因,我一直在收到帖子标题中的错误。我尝试过:`Arrays.fill(marked, false);`,我正在试图找出有多少个白色节点和黑色节点,连接在`blacknodes[]`中不存在的情况。
public class BlackWhite {
private static boolean[] marked;
public BlackWhite(Graph G, int s) {
marked = new boolean[G.V()];
dfs(G, s);
}
public static int count(Graph G, int[] blacknodes) {
int rw_count = 0;
for (int w : G.adj(blacknodes.length)) {
if (marked(w)) {
rw_count++;
}
}
return rw_count;
}
private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
dfs(G, w);
}
}
}
public static boolean marked(int v) {
return marked[v];
}
public static void main(String[] args) {
Graph G = new Graph(3);
G.addEdge(1, 2);
G.addEdge(4, 1);
G.addEdge(1, 8);
System.out.println(BlackWhite.count(G, new int[] { 1 })); // 应该打印出 3
}
}
英文:
When I run my code below, I keep getting the error from the title of this post, although I don't know why. I tried: Arrays.fill(marked, false);, I am trying to figure out how many white nodes and black nodes, connect that do not exist in the blacknodes[].
public class BlackWhite {
private static boolean[] marked;
public BlackWhite(Graph G, int s) {
marked = new boolean[G.V()];
dfs(G, s);
}
public static int count(Graph G, int[] blacknodes) {
int rw_count = 0;
for (int w : G.adj(blacknodes.length)) {
if (marked(w)) {
rw_count++;
}
}
return rw_count;
}
private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
dfs(G, w);
}
}
}
public static boolean marked(int v) {
return marked[v];
}
public static void main(String[] args) {
Graph G = new Graph(3);
G.addEdge(1, 2);
G.addEdge(4, 1);
G.addEdge(1, 8);
System.out.println(BlackWhite.count(G, new int[] { 1 })); // should print 3
}
}
答案1
得分: 0
你正在BlackWhite类的构造函数中初始化marked数组。但是在你的主方法中从未调用过new BlackWhite()。因此,当你调用静态的count方法时,你的marked数组仍然是null。
你应该像这样更改你的count方法。
public static int count(Graph G, int[] blacknodes) {
int rw_count = 0;
if (marked == null) marked = new boolean[G.V()];
for (int w : G.adj(blacknodes.length)) {
if (marked(w)) {
rw_count++;
}
}
return rw_count;
}
英文:
You are initializing the marked array at the Constuctor of BlackWhite class. But in your main method you never called new BlackWhite(). So your marked array is still null when you are calling the static count method.
You should change your count method like this.
public static int count(Graph G, int[] blacknodes) {
int rw_count = 0;
if(marked == null) marked = new boolean[G.V()];
for (int w : G.adj(blacknodes.length)) {
if (marked(w)) {
rw_count++;
}
}
return rw_count;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论