Java help: StringTokenizer + NoSuchElementException + frustration

Discussion in 'Community' started by King Cobra, Nov 24, 2003.

  1. King Cobra macrumors 603

    Mar 2, 2002
    First I would like to say, yes, this is for a part of my homework assignment (a few lines of code out of 8 classes, happy? :)). But I'm lost in how, in plain English, to:

    Test to see if the string in StringTokenizer contains something (say, a period), then to perform an action on it without getting a NoSuchElementException at runtime.

    I have yet to learn about using the try/catch block. But I don't think I need to use it, since I was given this assignment (and still have this small part to do) before learning about the try/catch.

    I have attached a test program (1 class) (requires Java programming app) as an example. Help me out.

    (Note: File works for Mac or PC.)

    Attached Files:

  2. benjaminpg macrumors regular

    Apr 21, 2002
    Salt Lake City, UT
    I didn't have a chance to read your code, but I'm guessing that you're getting a NoSuchElementException because you are calling nextToken() too many times. If it is in a for loop, you could have just made the maximum one too high; remember most indexes are zero-based.

    Hope that helps.
  3. King Cobra thread starter macrumors 603

    Mar 2, 2002
    Negative on the for loop. In psuedocode:

    if (character in the StringTokenizer is a period)
    //do something

    That's where the exception is thrown. If I enter a string without a period, the application (in the attachment) runs flawlessly.

    Now I noticed someone on these forums by the username of "Java" roam by this thread. You would think s/he would have responded by now. :D

    Anyways, I tried looking online, and I tried emailing my teachers. No working directions. Still looking for help.
  4. robbieduncan Moderator emeritus


    Jul 24, 2002
    You check that the tokenizer has more tokens correctly but within the check you call nextToken twice. You cannot do this! Only call nextToken once round the loop, or check more hasMoreTokens before calling the second time.

    Hope that helps,

Share This Page