![](/img/trans.png)
[英]char array to int array conversion in java generates null pointer exception
[英]Null pointer Exception in Java when assigning value to int array
當我將值分配給對象中的int數組時,我的代碼顯示了空指針異常:
public class Cage {
int Value;
String Operator;
int[] placeHolders;
}
Cage o = new Cage();
o.Value = Integer.parseInt(strSplit[0]);
o.Operator = strSplit[1];
for(int i=2;i<strSplit.length;i++) {
o.placeHolders[i] = Integer.parseInt(strSplit[i]);
}
您應該為placeHolders
創建一個int
數組,它只是一個聲明,而不是現在的定義。
o.placeHolders = new int[strSplit.length];
我想您想讓placeHolders
在索引的第一個中保留沒有null
值的值。
o.placeHolders = new int[strSplit.length - 2];
for (int i = 0; i < strSplit.length - 2; i++) {
o.placeHolders[i] = Integer.parseInt(strSplit[i + 2]);
}
您應該在使用它之前實例化int []對象:
int[] placeHolders = new int[100];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.