String tokenizing problem

This suddenly started happening last night and for the life of me, i do not know why.
when i start my applet, everything goes ok until my string tokenizer is called. Then the applet crashes and i get the following in the java console:
java.util.NoSuchElementException
     at java.util.StringTokenizer.nextToken(Unknown Source)
     at Player.authenticateUser(Player.java:98)
     at BlackJack.connect(BlackJack.java:575)
     at BlackJack.init(BlackJack.java:182)
     at sun.applet.AppletPanel.run(Unknown Source)
     at java.lang.Thread.run(Unknown Source)
Now, while i understand what the error means, i don't know why it is happening. The string to be tokenized is in the form: "name: x x id: x". Here's the code that handles it:
while(st.hasMoreTokens())
     while(!st.equals("id:"))
           if(!st.equals("name:"))
                name += st.nextToken();
     if(st.equals("id:"))
            memID = st.nextToken();
//Test string
System.out.println("input:" + input+"\n");This is so annoying now as i just can't see the problem. Any ideas?

Write down what you think the path through the code should be--how many times through the while, what happens each time, whether the if block is entered, what happens.
Then put in a bunch of print statements so you can see the path your code is following (or use a debugger). When you see what's different between what was expected and what's actually happening, you'll be able to find your logic bug.
Clearly something's wrong with the if and/or the while s.t. it's eating all the tokens and then still asking for more.

Similar Messages

  • Comparing input from command line to a String token problem

    Hi,
    I want to compare my input from the command line to a token.
    my command line looks like "java myProgram george bush president washington"
    The next command could be "java myProgram geoge president washington"
    Basically I have a text file which has a name, job and location field. The text file looks as follows
    jim, farmer, chicago
    paul, builder, texas,
    george bush, president, washington
    I am using string tokenizer with a "," as my field delimiter.
    My lecturer wants me to take the input from the command line so applets are out of the question. However even though there are 3 fields, args.length() could equal 4 because "george bush" is only the name but george is args[0] and bush is args[1]. Is there a way to have a delimiter on the command line instead of a space such a ",". Can anyone see any other way around this?
    Thanks

    1982. The year of.....wait for it.....
    Jack And Diane
    Tainted Love
    Key Largo
    Open Arms
    Do You Believe In Love
    Gloria
    Working For the Weekend and of course the GREATEST song of 1982...
    drum roll please......
    Heat Of The Moment.

  • Scan String Token Problem with leading Tokens

    Hi, I'm using the scan string for token to read in a string of tokens that contain a leading "*" char in front of each string and terminates when the token index = -2. This works great if I have say *12345*1234 and so forth, but if there is bad data, say 1234 without the leading "*" in front, the token index return value is still -1 and it returns data which I read in thinking it found the "*". Maybe I shouldn't use the string for token function since it's probably just designed for ending tokens and not data with leading tokens. Is there a way to make this work properly or should I use another method to search for leading tokens in a string?
    Thanks.
    Solved!
    Go to Solution.

    Here.  Try this one.  It does the same thing and uses exposed functions.
    The string functions look for something to mark the end of a string.  All languages that I know of do this.  So, like I said, remove the first element.  I recommend the Subarray function with the index set to 1 and length unwired.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Parse Message.png ‏10 KB

  • Guys I need some help. String token of a wired message

    well this is my code.
    code:
    import java.*;import java.util.StringTokenizer;import java.io.*; class stringtoken {         public static void main(String[] args) {         Runnable daemonRunner = new Runnable()        {                public void run()                        {                         while (true)                                {                    String red, green, blue, yellow, brown, v6, v7;                                        int ali=42;                                         String origtext = "accaa*b*dzddsf*,.sfsdf,a.a/.d,asd.,fa.a/.,/.**asdasdaadf";                                        StringTokenizer st = new StringTokenizer(origtext,"*");                                        try {                                        red = (String)("a" + st.nextToken());                                         green = (String)(st.nextToken());                                        blue = (String)(st.nextToken());                                        yellow = (String)(st.nextToken());                                        brown = (String)(st.nextToken());                                         System.out.println("Red : " + red);                                        System.out.println("Green : "+ green);                                        System.out.println("Red : " + blue);                                        System.out.println("Green : "+ yellow);                                        System.out.println("Blue : " + brown);                                        /////////////////////////////////[shaded section]/////////////////// String red1,red2;int ie=41; String aChar1 = new Character((char)ie).toString(); System.out.println("From above : Red" + red + " *** Will token -> " + aChar1); StringTokenizer st1 = new StringTokenizer(red, ")"); try {                                                red1 = (String)("After splitting 1 :" + st.nextToken());                                                red2 = (String)("After splitting 2 :" + st.nextToken());                                                System.out.println("Output : " + red1 + "&" + red2 );                                                        } catch (Exception ignored) { // (ERROR STATE) could not parse it                                                        } ////////////////////////////////[end of shaded section]/////////////////// int a = 0x41;int i=65; String aChar = new Character((char)i).toString(); System.out.println("Ending : " + aChar); } catch (Exception ignored) { // (ERROR STATE) could not parse it                                        } try {                                                Thread.sleep(1500);                                        } catch (InterruptedException ignored ) {                                        } } } }; Thread daemonThread = new Thread(daemonRunner); daemonThread.setDaemon(false); daemonThread.start(); try {                Thread.sleep(1000);                } catch (InterruptedException ignored) {                } } }
    let me explain a lil. The program is actually a daemon. It works fine. In the body run, that's the thingy which did string token. It works fine. But
    i am creating something that will split (1a) into 2 piece, and another will spilt the other piece.
    The senario, the daemon will receive a string, like "*abcde,1,2,3,hello%"
    where * = STX (ASCII 02) and % ETX (ASCII 03)
    the first loop will eliminate the STX, then seggregate the text to a loop, for example a=abcde, b=1, c=3, d=hello%.
    *what i managed to do is only string token the normal characters, not the ASCII characters 
    then the final loop will grab strtoken the % char.
    i have been trying tht for 1 whole days.. n e ideas guys ?
    thanks in advance.
    you could also post the edited text to [email protected]

    I have solve the problem. Thanks guys!
    import java.*;
    import java.util.StringTokenizer;
    import java.io.*;
    class stringtoken1 {
    public static void main(String[] args) {
         Runnable daemonRunner = new Runnable() {
              public void run() {
                        while (true) {
                        int STX=2, ETX=3, comma=44;
                        String stx = new Character((char)STX).toString();
                        String etx = new Character((char)ETX).toString();
                        String flag= null;
                        String ID= null;
                        String date= null;
                        String location= null;
                        String mobile= null;
                        String outtouser= null;
                        String message1=null;
                        String message2=null;
                        String origtext = stx+"1,001,17062005 16:16:16,Rawang, Telekom, Please stand by "+etx;
                        //System.out.println(origtext);
                                            String throwstx = new Character((char)STX).toString();
                                            StringTokenizer stxthrow1 = new StringTokenizer(origtext, throwstx);
                                            try {
                                                  message1 = (String)(stxthrow1.nextToken());
                                            catch (Exception ignoredthrowstx) {System.out.println(ignoredthrowstx);}
                                            String throwetx = new Character((char)ETX).toString();
                                            StringTokenizer etxthrow = new StringTokenizer(message1, throwetx);
                                            try {
                                                       message2 = (String)(etxthrow.nextToken());
                                            catch (Exception ignoredthrowstx) {System.out.println(ignoredthrowstx);}
                                            String chomma = new Character((char)comma).toString();
                                            StringTokenizer st = new StringTokenizer(message2,chomma);
                                            try {
                                                      flag = (String)(st.nextToken());
                                                      ID = (String)(st.nextToken());
                                                      date = (String)(st.nextToken());
                                                      location = (String)(st.nextToken());
                                                      mobile = (String)(st.nextToken());
                                                      outtouser = (String)(st.nextToken());
                                            catch (Exception ignoredcomma) {System.out.println(ignoredcomma);}
                                            System.out.println("Original Message : " + origtext);
                                            System.out.println("After STX : " + message1);
                                            System.out.println("After ETX : " + message2);
                                            System.out.println("Filtering");
                                            System.out.println("flag : " + flag);
                                            System.out.println("id : "+ ID);
                                            System.out.println("date : " + date);
                                            System.out.println("location : "+ location);
                                            System.out.println("mobile : " + mobile);
                                            System.out.println("message : " + outtouser);
                             try {
                              Thread.sleep(3000);
                              catch (InterruptedException ignored ) { }
    Thread daemonThread = new Thread(daemonRunner); daemonThread.setDaemon(false);
    daemonThread.start();
    try { Thread.sleep(1000);}
    catch (InterruptedException ignored){ }
    }for others guys as well :)

  • String Tokenizing Question

    Hello -
    I'm able to tokenize w/o any problems, save for when I run into consecutive instances of the character, a comma, that I am using for my delimiter. Here's a sample line:
    The,lazy,fox,,jumped,,,over,the,,,moon,,,,,
    So, if my string has values for each field that the tokenizer looks at, I have no problems, but if there are two or more commas (delimiters) in sequence, it breaks the tokenizer.
    So what I'd like to do barring a better/simpler solution is to print "N/A" or something if there is no data in that token and then continue on to assign each (valid) token to a String variable.
    Thanks...

    Like warnerja suggested/mentioned: try String's
    split(...) method:
    String s =
    "The,lazy,fox,,jumped,,,over,the,,,moon,,,,,";
    String[] tokens = s.split(",+");
    for(int i = 0; i < tokens.length; i++) {
    System.out.println("Token "+(i+1)+" =
    "+tokens);
    Except get rid of the "+" part, as that just makes it eat the empty tokens. Just use s.split(",")                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Parsing strings - baffling problem

    Hello, I have an issue with parsing tokenized strings that I am hoping someone can help me out on:
    I'm reading in a file which contains a line of the format n,n,n where n are integers (followed by other stuff.)
    I'm using the split() function to tokenize the string into an array of three strings.
    When I try to parse the strings to integers, I throw a NumberFormatException, but if I just read out the strings, they look fine.
    For example, if I read out the value of tokens[0] via System.out.println(tokens[0]), I get 1000, but ("1000"==tokens[0]) returns false;
    When try Integer.parseInt[tokens[0]), or:
    Integer.parseInt[tokens[0].trim())
    I get the exception, whereas:
    String tmp = "1000";
    Integer.parseInt[tmp) works fine.
    It seems that the two statements are identical. I'm kinda lost.
    Any pointers?
    Here is the code segment:
    {code}
         public boolean doOpen(String fName)
              File file = new File(fName);
         try
              String current ="";
              String delimiter = ",";
              BufferedReader br = new BufferedReader(new FileReader(file));
              current = br.readLine();
              if(current==null)
                   return false;
              else
                   System.out.println(current);
                   String[] tokens = current.split(delimiter);
                   if(tokens.length!=3)
                        System.out.println("Incorrect file format");
                        return false;
                   int tnX = 0,tnY=0,tN=0;
                   try
                        System.out.println("Trying first token: "+tokens[0]+".");
                        tnX = Integer.parseInt(tokens[0].trim());
                        System.out.println("Trying second token: "+tokens[1]+".");
                        tnY = Integer.parseInt(tokens[1]);
                        System.out.println("Trying third token: "+tokens[2]+".");
                        tN = Integer.parseInt(tokens[2]);
                   catch(NumberFormatException e)
                        System.out.println("Could not parse data: ("+tnX+","+tnY+","+tN+")");
                        return false;
                   nX = tnX;
                   nY = tnY;
                   grid = new char[nX][nY];
                   initGrid();
                   // parse input data and verify correct file
                   while ((current = br.readLine()) != null)
                        tokens = current.split(delimiter);
                        grid[Integer.parseInt(tokens[0])][Integer.parseInt(tokens[1])]=tokens[2].toCharArray()[0];
                   } // end while
                   System.out.println("File loaded successfuly");
                   return true;
         catch (IOException e)
         e.printStackTrace();
         return false;

    Hi everyone, I've got it figured now.
    There indeed was some invisible characters hidden in the string.
    When I added the code:
         char[] cs = tokens[0].toCharArray();
         for(int i = 0;i<cs.length;i++)
              System.out.println("Character "+i+": "+Character.getNumericValue(cs));
    I get as an output:
    *Character 0: -1*
    *Character 1: 1*
    *Character 2: -1*
    *Character 3: 0*
    *Character 4: -1*
    *Character 5: 0*
    *Character 6: -1*
    *Character 7: 0*
    *Character 8: -1*
    This comes from the way that the files are being generated: via a DataOutputStream.
    The following code inserts the hidden characters, and I can get around this by using a BufferedWriter
    OFFENDING CODE     File file = new File(fName);
         MapPoint[] points = getMapPoints();
         fos = new FileOutputStream(file);
         dos = new DataOutputStream(fos);
         dos.writeChars(new String(""+wX+","+wY+","+points.length+"\n"));
         for(int i = 0;i<points.length;i++)
              dos.writeChars(""+points[i].x+","+points[i].y+","+points[i].type+"\n");
    Thanks to everybody for all your help!
    - Andrew                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Split/remove characters for a string token

    How can a string token i.e. 2-234-56723-4 have the - removed so that the token is left with 2234567234?
    I tried to split it using "-" but that obviously doesnt work, because 234 will be a token, I just want to remove the - from the token.
    advice please.

    endasil wrote:
    Implode wrote:
    if I want 3-34-565456-4 to be 334565456 so that I can take each digit and do calculations with them, could I just split the string 334565456 using .split(""); which will give me splitArray[0]=3, splitArray[1] = 3, splitArray[2] = 4 etc.
    String someStr = "3-34-565456-4";
    String numsOnly = someStr.replaceAll("-", ""); //or someStr.replaceAll("[^0-9]", "");
    for ( char c : numsOnly.toCharArray() ) {
    int digit = c - '0';
    }Or
    for ( int i = 0; i < numsOnly.length(); i++ ) {
    int digit = Integer.parseInt(numsOnly.substring(i, i+1));
    What is "digit" ? and doesn't it re-assign a new number to digit each iteration?
    Im not sure how I will access each digit.

  • Setting input fields to an empty string BIG PROBLEM

    Hi Rob, thanks for your rerply, It makes sense alright, but I am using 2 seperate input fields. I have discovered what is causing the problem .
    After the user types into the inputfield and moves on to a different frame, I have set the input field to an empty string and this is what is causing the problem.
    I have tried setting the input field to an empty string in a movie script and on individual sprites and the first right answer is not excepted.I have to type in the right answer twice to get get a right response. I am actually using three seperate input fields in total, each with a different name and behavior. Even If I use one input field I still have the same problem. Its driving me crazey. Any Ideas.
    Anne

    I believe that the FIM Service always does trims on string, so you may be out of luck.
    What is your scenario / what are you trying to accomplish by setting a space in an attribute? A space is not an empty string in my definition.
    Regards, Soren Granfeldt
    blog is at http://blog.goverco.com | facebook https://www.facebook.com/TheIdentityManagementExplorer | twitter at https://twitter.com/#!/MrGranfeldt

  • String concat PROBLEM??? Please Help

    I have this strange Question regarding String concat
    If I say:
    String str = "Welcome";
    str.concat(" to Java");
    System.out.println(str);
    The output is: Welcome.
    How do I get the output to Welcome to Java??

    I have this strange Question regarding String concat
    If I say:
    String str = "Welcome";
    str.concat(" to Java");
    System.out.println(str);
    The output is: Welcome.
    How do I get the output to Welcome to Java??
    The problem is that String is immutable, The String you have held in str does not change, rather a new Srtring is returned. So all yo have to do is grab the new String
    str = str.concat("to Java");
    or use the new String without keeping it.
    ie
    System.out.println(str.concat("to Java"));

  • String concat problem

    Hi folks,-
    i know this question might be very simple but i just cannot see what i am doing wrong here.
    String stringA, stringB, stringC;
    stringA= new String();
    stringB= new String();
    stringC= new String();
    stringA = null;
    stringB = "TRUE";
    stringC = "Error:";
    stringA.concat(stringB); // my code stops and quits here w/o error
    // other codewhat is wrong here?
    thanks much

    could you then please explain the following?
    public String concat(String str)Concatenates the
    specified string to the end of this string.
    If the length of the argument string is 0, thenthis
    String object is returned. Otherwise, a new String
    object is created, representing a charactersequence
    that is the concatenation of the charactersequence
    represented by this String object and thecharacter
    sequence represented by the argument string.
    Examples:
    "cares".concat("s") returns "caress"
    "to".concat("get").concat("her") returns"together"
    Parameters:
    tr - the String that is concatenated to the end of
    this String.
    Returns:
    a string that represents the concatenation of this
    object's characters followed by the stringargument's
    characters.
    Throws:
    NullPointerException - if str is null.It returns a new String, which you are
    throwing away. Change your code like this:
    stringA = stringA.concat(stringB);
    and then you'd get somewhere.yes, it makes sense but the description does not say this.
    i think that will work but my problem is with the description of this
    concat operation on the java web site.
    thanks for the help

  • Search text file with 2 string tokens

    I am reading a text file which contains database records. I am able to search with lastname(the user enters it in the textfield using GUI frontend). this search useus stringtokenizers. take the users input and search all the tokens and see which token matches the key and prints that record. Can someone please give me some advice to do a search using both last name and first name at the same time. In this case i will have to do a seach using 2 tokens which i dont know how to do. thanks.

    Here is the snippet of my code. Can someone please take a look at it.
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ":", false);
    Vector row = new Vector();
    String lineTemp;
    while (st.hasMoreTokens()) {
    if (st.nextToken().trim().equalsIgnoreCase(userinput)) {
    //System.out.println(dbRecord);
    StringTokenizer tempst = new StringTokenizer(dbRecord, ":", false);
    while (tempst.hasMoreTokens()){
    row.addElement(tempst.nextToken());
    dataVector.addElement(row);
    }

  • String check problem

    I have a doozy of a problem on my hands. My company has introduced a password policy that every user must me now. Some of my criteria is that a password must contain at least one symbol and at least one number. In 10g I can use REGEXP_LIKE function, but I am running 9i. I have tried to use translate, OWA_PATTERN function, everthing. How can I take a string variable, and test to see if there is a symbol in the text or a number. I want to be able to return a true/false value?
    Please advise?

    Like Kamal says, use built-in functionality FIRST.
    Failing that, presumably you would write something like this (I forget the exact naming standard for the password verify function).
    CREATE FUNCTION valid_password (
       p_password IN VARCHAR2)
       RETURN BOOLEAN
    IS
       FUNCTION contains_at_least_one (
          p_string IN VARCHAR2,
          p_characters IN VARCHAR2)
          RETURN BOOLEAN
       IS
       BEGIN
          RETURN LENGTH (TRANSLATE (p_string, 'X' ||
            p_characters, 'X')) < LENGTH (p_string);
       END;
    BEGIN
       RETURN contains_at_least_one (p_password, '0123456789')
          AND contains_at_least_one (p_password, '!£$%^&*(){}~@??|<>');
    END;

  • String overlapping problem in mx:List caused by wordWrap

    I'm using mx:List to display String items. The dataProvider is XMLListCollection. Some of the String is long so it takes more than one rows. I use the wordWrap to display the long String in more than one rows. The problem is that the next String item will overlapping with the long String. The mx:List can not adjust the vertical space for the Strings that needs more than one rows dynamically. Any suggections?

    Here is solution: variableRowHeight="true"

  • String Tokinzer problem

    Hi ,
    I wanted to toknize following string using token "#,"
    ABC#,A (C, D, E, F) & G#,XYZ (FGH)#, DEF(CDE)#, QPR
    i.e i need
    ABC
    A (C, D, E, F) & G etc.........
    but it also tokinzes for occurance of ,
    it returns
    ABC
    A(C
    D
    Please suggest

    StringTokenizer can only tokenize on single characters. Try [String.split|http://java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)] instead.
    Edit:
    Too slow :-(

  • String offset problem

    Hi,
    I'm using 1.4.2 at the moment.
    I got the problem below and have no idea how to solve it. The program portion is:
    String x = node.getText();
    The node.getText() should contain value = "\n\r"
    However, it always return me "\r" only.
    I checked with the debugger and found that when I change the offset value of x to 0, it can return me "\n". However, the original offset value is always kept as 1. That's the reason why it always return me "\r".
    Can anyone help and tell me how to get the value "\n" in this case, i.e. any String method which I can check and get the offset value 0 from the string x.
    Thanks million in advance.
    Regards,
    Eric

    Can anyone help and tell me how to get the value "\n"
    in this case, i.e. any String method which I can
    check and get the offset value 0 from the string x.
    x.charAt(0);is probably what you mean.

Maybe you are looking for

  • Method GUI_DOWNLOAD not creating CRLF at end-of-each-line of output

    Hello SDN Community,  has anyone experienced CL_GUI_FRONTEND_SERVICES=> GUI_DOWNLOAD not putting the CRLF at end of exported lines?  This can be seen when you view the output file in notepad (the file contents wrap) or an editor with hex view enabled

  • Multiple Java Console open in JRE 1.7 on IE8 browser

    Our application has interface in HTML where we used LiveConnect for Java and Java Script using Applet. Single HTML page loaded multiple Applet. When we access our application using JRE7 on IE8 then it opens multiple Java console window which result t

  • Why no CS6 on my PC?

    I have CS6 as a box since last year, I upgraded to CC. Now I have a Problem with second installation on my PC. There is only CC in the list of programs. On my Mac there are both, CC and CS6. What is the reason for this? I thougt, it should be possibl

  • SM35 Batch Still Showing in Processing Mode (how to stop)

    Dear SAP Expert, We have one batch file (created from input BDC) where records contained 1500. Due to some power SAP was shut down and when user checked in SM35 the batch was showing in still processing mode. Aftre hours waiting user used - release o

  • Func modules vs. BAPIs; What is a BADI? When do we use it?

    Hi experts, I have some ABAP questions and need your help to answer them. 1. What is the difference between a func. module and a BAPI? 2. What is a BADI and in which circumtanse we use it? How can I view a BADI example? 3. What is a WorkFlow and in w