Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to convert string arrays with following structure:

static String[] lines = {
                          "@1      var_decl         name: testStr  parent: @7",            
                          "                         srcp: Auto.cpp:6         "
                        };

into Java objects with following structure:

class Token {
   String type;
   String name;
   String source;
   Token parent;
}

So far I'm parsing this in this way:

Token parseLines(String[] lines) {

    String[] firstElements = lines[0].split(" ");
    String[] secondElements = lines[1].split(" ");

    Token newToken = new Token();

    newToken.type = firstElements[6];
    newToken.name = firstElements[16];
    String parentName = firstElements[19];
    newToken.parent = getParent(parent); // find parent by name
    newToken.source = secondElements[26];
    return newToken;
}

As you can see, this is far from elegant. How can I improve this?

share|improve this question
    
@Heslacher Yup, fixed. –  Kao Jan 12 at 8:50
1  
Not completely check length –  Heslacher Jan 12 at 8:53
    
The code seems obviously broken in other ways too. –  200_success Jan 12 at 10:43
    
I've rewritten the whole code. –  Kao Jan 13 at 9:56

1 Answer 1

My approach would start by looking something like the code below. Obviously whatever you wind up with should be in its own class/method to do the mapping from String[] to Token.

public final class Test {

    private static final int TYPE_COLUMN = 1;
    private static final int NAME_COLUMN = 3;
    private static final int PARENT_COLUMN = 5;
    private static final int SOURCE_COLUMN = 7;

    public static void main(final String[] args) {
        final String[] lines = {
                "@1      var_decl         name: testStr  parent: @7",
                "                         srcp: Auto.cpp:6         "
              };

        final String[] values = (lines[0] + lines [1]).split("\\s+");
        System.out.println(All Values:" + java.util.Arrays.toString(values));
        System.out.println("Type: " + values[TYPE_COLUMN]);
        System.out.println("Name: " + values[NAME_COLUMN]);
        System.out.println("Parent: " + getParent(values[PARENT_COLUMN]));
        System.out.println("Source: " + values[SOURCE_COLUMN]);

    }

    private static String getParent(final String parentId) {
        return "Parent";
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.