-6

I need a program that expands a string into single lines. Operators "\|" and "," delimit colums.

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 Answers2

3

expandedLine is not initialised anywhere (except for null). Thus, the access to the elements yields a null pointer exception.

Howard
  • 38,639
  • 9
  • 64
  • 83
0

Adding to @Howard explanation .. you need to initialize the expandedLine array before you add anything to it . .so you must do something like

String[] expandedLine = new String[100]; before using expandedLine[i]=v[p];
The number 100 inside the new String[..] statment defined the size of the array, you need to decide

user2720864
  • 8,015
  • 5
  • 48
  • 60