开发者

Java Merging two sets of arrays from a user input -- How do I deal with nulls?

I'm writing a program for CS class assignment.

Basically it's a method that takes to command line arguments. Something like a CSV, so to call the call I do merge followed be the csv's.

eg merge 1,2,3,4 5,6,7,8

This will do two things. 1) it takes each list as an array argument then merges into 1 big array, 2) it sorts that array.

Here's the catch, from the command line we need to deal with null values. So a user could feed in:

merge 1,2,,3,4 5,6

How do I deal with this?

example of the error output:

Enter commands:
merge 12,,2 43
java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.开发者_Go百科parseInt(Integer.java:493)
    at java.lang.Integer.parseInt(Integer.java:514)
    at CmdInterpreter.strArrayToIntArray(CmdInterpreter.java:143)
    at CmdInterpreter.getIntArray(CmdInterpreter.java:130)
    at Assign1.processOneCommand(Assign1.java:99)
    at CmdInterpreter.processCommands(CmdInterpreter.java:198)
    at CmdInterpreter.processCommands(CmdInterpreter.java:230)
    at CmdInterpreter.ooMain(CmdInterpreter.java:243)
    at MyAssign1.main(MyAssign1.java:20)


When you call parseInt, wrap the call in a try/catch block. If you catch a NumberFormatException, throw away the string and decrement the number of values.

Edit: How do you do that? Something like this:

int[] extractValues(String arg) {
    String[] sValues = arg.split(",");
    int n = values.length;
    int[] values = new int[n];
    for (int i = 0; i < n; ++i) {
        try {
            values[i] = Integer.parseInt(sValues[i]);
        } catch (NumberFormatException e) {
            --n;
        }
    }
    // reallocate values array if there were problems
    if (n < values.length) {
        int[] tmp = new int[n];
        System.arraycopy(values, 0, tmp, 0, n);
        values = tmp;
    }
    return values;
}


You need to handle the event that there is no integer there. It appears that you are simply blindly looping through the input without checking for it's integrity, which is why you are getting an exception.

The proper way to do this would be to set up a checking mechanism which ensures that the current data you are parsing is valid (in this case, meaning it is an Integer).

I am leaving my answer very vague because you explicitly stated that this is for a school assignment, so you should take this answer and use it to experiment and learn to implement a proper solution.


I found out you can feed in either list1 as null or list2 or both. But not elements of those arrays... Meaning I was trying something that would not be a problem for this assignment.


StringUtils.split should give you about ten ways to do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜