Dogo-San
Dogo-San

Reputation: 375

store tuples in a list using jcommander

I tried to store string tuples in a arraylist, when in the terminal I put the following command

> java Main -P A,60 B,90 C,50 D,40 E,70 F,100 G,1000

, but the elements are separated in two when the program finds a comma, so I get this output

A
60
B
90
C
50
D
40
E
70
F
100
G
1000

and I tried to get this output

A,60
B,90
C,50
D,40
E,70
F,100
G,1000

how I can fix it? here is my code

import java.util.ArrayList;
import java.util.List;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;


class Main {

    @Parameter(names={"-P"}, variableArity=true)
    public List<String> values = new ArrayList<String>();

    public static void main(String ... argv) {
        Main main = new Main();
        JCommander.newBuilder()
            .addObject(main)
            .build()
            .parse(argv);
        main.run();
    }

    public void run() {
      for (String val: values) {
        System.out.println(val);
      }
    }
}

Upvotes: 0

Views: 544

Answers (1)

Julian
Julian

Reputation: 2907

JCommander splits up arguments using the comma by default: See custom types - converters and splitters -> Splitting for details. This is what is causing your problem. One way to solve it is to provide an IParameterSplitter which doesn't split:

public class Main {
    private static final class NonSplittingSpliter implements IParameterSplitter {
        public List<String> split(String value) {
            return Collections.singletonList(value);
        }
    }
    @Parameter(names={"-P"},
            splitter = NonSplittingSpliter.class,
            variableArity = true)
    public List<String> values = Collections.emptyList();

    public static void main(String ... argv) {
        Main main = new Main();
        JCommander.newBuilder()
                .addObject(main)
                .build()
                .parse(argv);
        main.run();
    }

    public void run() {
        for (String val: values) {
            System.out.println(val);
        }
    }
}

This should solve your problem.

Upvotes: 1

Related Questions