gpt4 book ai didi

java - 检查数组时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 23:25:44 25 4
gpt4 key购买 nike

我对 java 很陌生,但我必须初始化一个大小为 n 的二维数组,在本例中为 10。初始化后,我想检查对角线条目是否为假,以及是否将它们设置为真。之后我想返回 i 的值。

这是我编码的:

首先初始化数组:

public static void init(int n) {
boolean friendship[][] = new boolean[n][n];}

在我尝试之后:

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;
}

可悲的是它的 throw :

Exception in thread "main" java.lang.NullPointerException
at x.SocialNetwork.addUser(SocialNetwork.java:18)
at x.SocialNetwork.main(SocialNetwork.java:53)

我可以做什么来解决这个问题?

PS:抱歉英语和格式不好。

最佳答案

我假设您有一个名为friendshipstatic字段。在这个方法中

public static void init(int n) {
boolean friendship[][] = new boolean[n][n];
}

您正在声明一个新的本地friendship变量,即shadowing 静态 成员。因此,static friendship 字段仍为 null,当您尝试在 addUser 中访问它时,您会得到一个 空指针异常

使用

public static void init(int n) {
friendship = new boolean[n][n];
}

再次假设你有类似的东西

public static boolean[][] friendship;
<小时/>

在此

if ( friendship[i][i] = false) {

您实际上是将 friendship[i][i] 设置为 false。相等运算符是==

<小时/>

这就是我对你们类(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;
}
}

关于java - 检查数组时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20033468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com