第40行的空指针异常

时间:2013-12-17 05:42:31

标签: java eclipse

我需要一个将字符串扩展为单行的程序。     运营商" \ |"和","分隔字符串。

IN

A10,A2 ||||| F4 | G5 | H107 || J1 | K13,K3 ||||

OUT 

A10 ||||| F4 | G5 | H107 || J1 | K13 |

A10 ||||| F4 | G5 | H107 || J1 | K3 |

A2 ||||| F4 | G5 | H107 || J1 | K13 |

A2 ||||| F4 | G5 | H107 || J1 | K3 |

   import java.io.*;

public class CitesteLinii{
static String[] expandedLine = null;
static String[][] lineToExpand = null;

static int N = 0;

static String toLine() {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i< N; i++) {
        if (i>0) {
            sb.append("|");
        }

        String[] list = expandedLine;
        for (int pi = 0; pi <list.length;pi++) {
            if (pi>0) {
            sb.append(",");
            }               

            sb.append(list[pi]);
        }
    }
    return sb.toString();
}

static void expandLine(int i) {
    if (i == N) {
        System.out.print(toLine());
    }
else {
    String[] v = lineToExpand[i];

    if (v == null || v.length == 0) {
        expandedLine[i] = "";
        expandLine(i + 1);
    } else {
        for (int p = 0; p < v.length; p++) {
            expandedLine[i]=v[p];
            expandLine(i + 1);
            }
        }
    }
}

public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new FileReader(new File("in.txt")));

    try {       
        String line = in.readLine();
        while (line!=null) {
            String[] parts = line.split("\\|");       
            N= parts.length;       
            lineToExpand = new String[N][];       

            for (int ai = 0; ai < N; ai++) {           
                String[] v = parts[ai].split(",");
                System.out.println(parts[ai]+' ');
                lineToExpand[ai] = v;
                }           
            expandLine(0);     

            line = in.readLine();
        }
    }
    finally {
        in.close();
        }
}     
}

2 个答案:

答案 0 :(得分:2)

expandedLine未在任何地方初始化(除了null)。因此,对元素的访问会产生空指针异常。

答案 1 :(得分:0)

添加@Howard解释..您需要在添加任何内容之前初始化expandedLine数组。所以你必须做一些像

这样的事情 在使用String[] expandedLine = new String[100];之前

expandedLine[i]=v[p];100声明中的数字new String[..]定义了数组的大小,您需要决定