为什么我的数组包含所有null? 在这个代码区域
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken();
String loo = tokFix[i];
i++;
System.out.println(loo);
System.out.println(tokFix[i]); }
当我这样做时
System.out.println(loo);
它将正确输出数组中包含的每个字符串值
然而,当我做S
时System.out.println(tokFix[i]);
它只会给我所有空值的输出
导致这种事情发生的两者有什么区别?
代码:
public static String[] parseFixMsg(String fixMsg1,String fixMsg2){
int i = 0;
int size = getArraySize(fixMsg1);
String[] tokFix = new String[size];
StringTokenizer st = new StringTokenizer(fixMsg2,(Character.toString((char)01))+"]");
st.nextToken();
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken();
String loo = tokFix[i];
i++;
System.out.println(loo);
System.out.println(tokFix[i]); }
return tokFix;
}
public static int getArraySize(String fixMsg){
int size = 1;
StringTokenizer st = new StringTokenizer(fixMsg,(Character.toString((char)01))+"]");
st.nextToken();
while (st.hasMoreTokens()) {
st.nextToken();
size+=1;
}
return size;
}
答案 0 :(得分:2)
i++;
指向sys.out语句中的下一个元素。在循环结束时做++ i。
答案 1 :(得分:2)
您需要稍微移动下面提到的行,因为您在打印前增加变量i
。 sysout中的toFix[i]
始终指向尚未初始化/分配的下一个元素:
System.out.println(tokFix[i]);
以下是您需要的更新代码
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken();
String loo = tokFix[i];
System.out.println(tokFix[i]);
i++;
System.out.println(loo);
}
答案 2 :(得分:2)
以下是逐行解释正在发生的事情。让我们来看看i = 2
:
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken(); // Now tokFix[2] is not null
String loo = tokFix[i]; // Again, so far so good; you're storing tokFix[2] to loo
i++; // You've incremented i to 3 now! Here's your problem, as seen in the following:
System.out.println(loo); // Prints out tokFix[2]
System.out.println(tokFix[i]); // Prints out tokFix[3], which is null
}
正如其他人所说,只需将增量移动到循环的末尾。
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken();
String loo = tokFix[i];
System.out.println(loo);
System.out.println(tokFix[i]);
i++; // Now we increment
}
答案 3 :(得分:0)
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken(); // let's say i=1
String loo = tokFix[i]; // now loo= tokFix[1]
i++; // now i=2
System.out.println(loo); // print loo value
System.out.println(tokFix[i]); } // what happen here??? print tokFix[2]. But still not assign a value to that
所以将其更改为
while (st.hasMoreTokens()) {
tokFix[i] = st.nextToken();
String loo = tokFix[i];
System.out.println(loo);
System.out.println(tokFix[i]);
i++;
}