1

为什么我的数组包含所有空值?在这个代码区域

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

4 回答 4

2
i++;

指向 sys.out 语句中的下一个元素。在循环结束时执行 ++i。

于 2013-07-12T17:40:15.470 回答
2

您需要将下面提到的行移到上方一点,因为您i在打印之前增加了变量。您toFix[i]的 in sysout 始终指向下一个尚未初始化/分配的元素:

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);
 }
于 2013-07-12T17:42:13.690 回答
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
}
于 2013-07-12T17:46:26.270 回答
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++;
         }
于 2013-07-12T17:54:34.283 回答