开发者

Basic home work question what am I doing wrong

/* Method: findName() */
/**
 * Finds the name of the entry and sets it to the name variable.
 */
    private void findName(String line){
        end = line.indexOf(" ");
        name = line.substring(0,end);
    }

/* Method: findDecades() */
/**
 * Finds the name of the entry and sets it to the name variable.
 */
    private void findDecades(String line){
        for(int i = 0; i<NDECADES; i++){
            int start = end + 1;
            end = line.indexOf(" ",start);
            String decadeTemp = line.substring(start, end);
            data[i] = Integer.parseInt(decadeTemp);
        }
    }

Line looks like the following:

Sam 58 69 99 131 168 236 278 380 467 408 466

When I run the code the first meth开发者_运维百科od runs fine but then it throws an error exception when it reaches the line:

            String decadeTemp = line.substring(start, end);

edit:

the error that is throw is:

throw new StringIndexOutOfBoundsException(endIndex - beginIndex);


Add another line

        end = line.indexOf(" ",start);
        System.out.println("Doing substring of "+start+" to "+end);  // new line
        String decadeTemp = line.substring(start, end);

That should make it obvious. I'm guessing that end is -1, which means you didn't find a space, and NDECADES is too big.


I suspect (without further info) that you're running off the end of your string during

line.substring(start, end);

and so your boundary conditions aren't right. I would print out the start/end values and determine from that what's wrong. I would strongly recommend, btw, that in questions like this you publish the exception/stacktrace you're getting.

Going further, you may find the above easier by using String.split(" ") and iterating across the resultant array. That tends to be less error prone since you can just use a for loop across the array, and not have to keep track of start and end pints (which I always get wrong, for what it's worth).

(as this is homework, I'm assuming the input strings are well-formed. Otherwise you'll have to cater for a variety of inputs and a more robust solution would be required)


What if line doesn't have any spaces in it? Or what if it doesn't have any spaces in it from start on out?


You might want to take a look at some of the other methods on String that could make this a bit simpler (String.split() comes to mind).


Problem solved NDECADES was one space too big.


To start finding the problem yourself you should have a look at the Javadoc for String#indexOf and String#substring, in particular about what happens in border cases (like nothing is found, etc).


You need to do some checks, e.g.

if (start > 0 && end > 0 && end < length).

You also need to do check if decadeTemp is numeric.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜