我的代碼中出現NullPointerException錯誤。我真的不知道它爲什麼會發生。這只是代碼的一個示例,如果需要,我可以發佈完整版本。Java - 空指針異常錯誤
private static final Scanner in=new Scanner(System.in);
public static void main(String[] args) {
int n1=lerTamanho();
String [] vec1=new String [n1];
readVector(vec1); -> Line 11
}
private static int lerTamanho() {
System.out.print("Number: ");
int num=in.nextInt();
while (num<=0) {
System.out.print("Error! Number: ");
num=in.nextInt();
}
return num;
}
private static void readVector(String vec[]) {
int cont=0;
String s;
do {
System.out.print("Name: ");
s=in.nextLine();
if (validate(s,vec)) { -> Line 30
vec[cont]=s;
cont++;
} else {
System.out.println("That name already exists!");
}
} while (cont<vec.length);
}
private static boolean validate(String s, String vec[]) {
boolean success=true;
for (int i=0; i<vec.length; i++) {
if (vec[i].equalsIgnoreCase(s)) { >-> Line 44
return !success;
}
}
return success;
}
錯誤我越來越:
Exception in thread "main" java.lang.NullPointerException
at javaapplication63.JavaApplication63.validate(JavaApplication63.java:41)
at javaapplication63.JavaApplication63.lerVetor(JavaApplication63.java:30)
at javaapplication63.JavaApplication63.main(JavaApplication63.java:11)
東西一定叫做驗證傳遞null作爲S或VEC –
如果你指出了這行是第41 – biziclop
貌似是'vec'或單曲這將是非常有用的'(在'validate'方法中)尚未初始化。您可能想要發佈'lerVector()'方法的代碼。 – Josh