StringTokenizer

I'm trying to learn about StringTokenizer and I have a few questions.
1) Can someone give me some good links to learn about the subject?
2) By the way, does anyone else find Suns documentation confusing? Or am I just not advanced enough? For example: http://java.sun.com/j2se/1.3/docs/api/java/util/StringTokenizer.html
gives the code snippet:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
     println(st.nextToken());
Why do they use an incomplete print statement?
'println();' instead of 'System.out.println();'
To me ten minutes to figure out what was wrong.
3) Which is a better import statement?
import java.util.*; // Is this too general and inefficient?
or
import java.util.StringTokenizer; // Is this too specific?

wynship wrote:
If you put "import java.lang.System.out.*", then you can just use "println" by itself. If you do "import java.lang.System.*", then you use "out.println". You get the idea?
wynship, have you every try it? You can't do that. You can only import classes not methods or variables in a class.
igottaknow wrote:
Can someone give me some good links to learn about the subject?
StringTokenizer is easy to use. There are only three constructors and size methods. If you read the doc carefully, you should be able to understand.
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
    println(st.nextToken());
}igottaknow, this is only a part of a method (or main), you should not confusing yourself when you see codes like this. When you see this kind of code, you should consider the method or variable is already declared.
Which is a better import statement?
This is personal preference. Personally, I like to write out what class(es) I am importing, so it is easy to track down errors. However, if you are importing many classes in the same package and do not like to write out every classes you import, you could use the asterisk. As for whether using asterisk is inefficient or not, it doesn't matter because import is not the include in C/C++.

Similar Messages

  • Form feed, null and StringTokenizer

    is form feed recognized as null when using the StringTokenizer?
    i currently have my StringTokenizer set with a blank space and i am attempting to read until the value is (EOF) null and while it hasMoreTokens. the text file that i am reading from spans across several pages. my code falls out of my loop when it hits the last space on my first page.

    a form feed (\f) is not a null but that shouldn't be stopping the StringTokenizer, I suspect that the manner in which you're reading in the data may be the culprit. Try to use the BufferedReader class to read your file.
    V.V.

  • StringTokenizer vs. split and empty strings -- some clarification please?

    Hi everybody,
    I posted a question that was sort of similar to this once, asking if it was best to convert any StringTokenizers to calls to split when parsing strings, but this one is a little different. I rarely use split, because if there are consecutive delimiters, it gives empty strings in the array it returns, which I don't want. On the other hand, I know StringTokenizer is slower, but it doesn't give empty strings with consecutive delimiters. I would use split much more often if there was a way to use it and not have to check every array element to make sure it isn't the empty string. I think I may have misunderstood the javadoc to some extent--could anyone explain to me why split causes empty strings and StringTokenizer doesn't?
    Thanks,
    Jezzica85

    Because they are different?
    Tokenizers are designed to return tokens, whereas split is simply splitting the String up into bits. They have different purposes
    and uses to be honest. I believe the results of previous discussions of this have indicated that Tokenizers are slightly (very
    slightly and not really meaningfully) faster and tokenizers do have the option of return delimiters as well which can be useful
    and is a functionality not present in just a straight split.
    However. split and regex in general are newer additions to the Java platform and they do have some advantages. The most
    obvious being that you cannot use a tokenizer to split up values where the delimiter is multiple characters and you can with
    split.
    So in general the advice given to you was good, because split gives you more flexibility down the road. If you don't want
    the empty strings then yes just read them and throw them away.
    Edited by: cotton.m on Mar 6, 2008 7:34 AM
    goddamned stupid forum formatting

  • Stringtokenizer, swing and memory

    i lately found that the stringtokenizer eats up lots of memory, i tried to set vars to null and called sys gc quite often but they didnt seem to be of much help.
    ok, here is what i was doing: i read in a quite a big txt file, about 400k lines, and then parsed each line using stringtokenizer, everything happened in while loops, lots of objects but all small ones. i had to xmx lots of memories to it in order to run it. and it became much worse when i put it into multi threaded swing app. if you are a swing expert, or stringtokenizer expert, please shed some light.

    Dang it! Sun zapped a bunch of posts!
    Anyway, here again is a sample pgm posted earlier (which got zapped) showing some of the benefits of the finally block, for which the idiot daFei could not come up with an intelligent answer to refute it (he STILL has a beef with the finally block, claiming it is only "syntactic sugar", and still moronically implies that all methods must handle all exceptions, which is absurd in that no exceptions could ever be THROWN then!)
    import java.io.File;
    import java.io.IOException;
    class SillyQuestionException extends Exception {
      public SillyQuestionException() {
        super("That's a silly question.  Of course!");
    class Guru {
       * Responds to a question/statement.  A temporary file is created
       * during execution, and deleted upon return (unless daFei dorks
       * with the implementation!)
       * @param request the question/statement for Guru to respond to
       * @return the Guru's response
       * @throws SillyQuestionException if the Guru determines you're
       * asking a silly question,
       * to which the answer should be obviously YES
      public static String respond(String request)
        throws SillyQuestionException {
        File f = new File("daFei.is.an.idiot");
        try {
          System.out.println("  Guru is thinking...");
          f.createNewFile();
          // let's just assume we needed to write stuff to this file in
          // order to process the request...
          // now the actual end of processing
          if ("is daFei an idiot".equals(request))
            throw new SillyQuestionException();
        catch (IOException e) {
          System.out.println("Error occurred creating/writing to " +
            "temp file, but graceful recovery is possible");
          e.printStackTrace();
          return "I'll have to get back to you on that one.  " +
            "Ask me again later.";
        finally {
          // this is NECESSARY to GUARANTEE deletion of the temp file,
          // otherwise this statement would have to be duplicated at all
          // possible return points.
          System.out.println("  Guru has processed your request...");
          if (f != null)
            f.delete();
        System.out.println("  will this get printed EVERY time?  " +
          "NO IT WILL NOT!");
        return "daFei has fish turds in his brain";
    public class Demo {
      public static void main(String[] args) {
        String[] questions = {
          "what statement best describes daFei",
          "what kind of turds does daFei have in his brain",
          "is daFei an idiot",
          "won't get to this question"
        try {
          for (int i = 0; i < questions.length; ++i) {
            System.out.println("Question: " + questions);
    System.out.println("Response: " + Guru.respond(questions[i]));
    catch (SillyQuestionException e) {
    System.out.println("I have finally asked the Guru a silly " +
    "question, and will stop now");
    System.out.println("Here's what Guru had to say to the last " +
    "question: " + e);

  • Faster split than String.split() and StringTokenizer?

    First I imrpoved performance of split by replacing the String.split() call with a custom method using StringTokenizer:
                    final StringTokenizer st = new StringTokenizer(string, separator, true);
                    String token = null;
                    String lastToken = separator; //if first token is separator
                    while (st.hasMoreTokens()) {
                        token = st.nextToken();
                        if (token.equals(separator)) {
                            if (lastToken.equals(separator)) { //no value between 2 separators?
                                result.add(emptyStrings ? "" : null);
                        } else {
                            result.add(token);
                        lastToken = token;
                    }//next tokenBut this is still not very fast (as it is one of the "hot spots" in my profiling sessions). I wonder if it can go still faster to split strings with ";" as the delimiter?

    Yup, for simple splitting without escaping of separators, indexOf is more than twice as fast:
        static private List<String> fastSplit(final String text, char separator, final boolean emptyStrings) {
            final List<String> result = new ArrayList<String>();
            if (text != null && text.length() > 0) {
                int index1 = 0;
                int index2 = text.indexOf(separator);
                while (index2 >= 0) {
                    String token = text.substring(index1, index2);
                    result.add(token);
                    index1 = index2 + 1;
                    index2 = text.indexOf(separator, index1);
                if (index1 < text.length() - 1) {
                    result.add(text.substring(index1));
            }//else: input unavailable
            return result;
        }Faster? ;-)

  • Missing Value using HashMap and StringTokenizer

    class StringToken
         String Message = "a b Germany";
         HashMap <String,String> map;
    StringTokenizer token;
         public StringToken()
              try
              token = new StringTokenize(Message);
                   map = new HashMap <String,String>();
                   map.put("a","Adelaide");
                   map.put("b","Auckland");
    while (token.hasMoreToken())
                        System.out.print (map.get(pesan.nextToken())+" ");          
              catch(Exception e)
         public static void main(String[] args)
              new StringToken();
    The output like this :
    Adelaide Auckland null
    What i want like this:
    Adelaide Auckland Germany
    The problem is,How to display all value of Message? cos There's no Germany key..i want to make some condition like this, if there's no key in the Hashmap, the value still displayed originally..
    At my code the problem is, if there's no key in hashmap,output wont display the word..
    Thanks Guys...

    Two options:
    1) Instead of
    System.out.print(map.get(pesan.nextToken()));do
    String token = pesan.nextToken();
    String value = map.get(token);
    if (value==null) value = token;
    System.out.print(value);2) Implement a new Map which provides this behavior.
    Cheers

  • Polynomial and Stringtokenizer

    I'm stuck on a homework problem involving a polynomial. The part I'm stuck on is where you're given a string in the form of a polynomial and you need to split it up into it's different terms.
    One constructor, Polynomial(String poly), is somewhat tricky. For this constructor you must extract the required information from the string passed as an argument. Stylistic issues are important in defining the valid parameters for this constructor.
        * ax^n+bx^(n-1)+c1x^(n-2)+...+d , the string is a valid polynomial.
        * No two terms have the same exponent.
        * No terms with coefficient 0 (2x^2+1 is valid input for 2x^2+0x^1+1).
        * Terms with coefficient of 1 omits the 1 (x^3+x^2 is valid).
        * The x^1 term omits the exponent 1 (2x^3+3x is valid).
        * The x^0 term, the constant term, omits everything but the coeficient (2x^3+3x+1 is valid).
        * There are no occurrences of contiguous plus and minus signs (+- and -+ not allowed).
        * The leading positive sign on the initial term is unnecessary: 5x^2+4x+2 is valid, not +5x^2+4x+2
        * There are no duplicate terms, i.e., there is at most one term for a given power.I think I know where to start, that's using a StringTokenizer. But from there I'm lost. Any help would be greatly appreciated.

    Ordinarily, I would advise against using StringTokenizer for parsing mathematical expressions, but your requirements are so simple that it should suffice.
    You have one or more terms separated by plus or minus signs--that's your delimiter. You have to keep the delimiter (instead of discarding it as StringTokenizer usually does) so you can apply the correct sign to the following term. And you have to handle an optional minus sign at the beginning of the expression (i.e., the first "term" might be the empty string, and should be ignored).
    Does that help?

  • FileReader and StringTokenizer

    what I'm trying to do is to read String and Double date in a txt document here my code:
    import java.io.*;
    import java.util.*;
    public class partie1 {
         static final int limite_colones=10;
         static final int limite_lignes=10;
         static final int limite_matieres=5;
         static final int limite_eleves=15;
         static final String titre="�cole secondaire Cartierville";
         static String nomEleve[]=new String[limite_eleves];
         static double notesEleve[][]=new double[limite_eleves][limite_matieres];
         public static void main(String[] args)throws IOException {
              String ligne,ficEleve="c:/ficEleves.txt";
              BufferedReader ficnomlogique=new BufferedReader(new FileReader(new File(ficEleve)));
              while ((ligne=ficnomlogique.readLine())!=null){
                   StringTokenizer ligneTemp=new StringTokenizer (ligne,":");
                   for(int i=0;i<15;i++){
                        nomEleve=ligneTemp.nextToken();
                        System.out.println(nomEleve[i]);
                        for(int j=0;j<5;j++){
                             notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
                             System.out.println(notesEleve[i][j]);
    and this is what they give me as error message:
    Alain
    100.0
    90.0
    88.0
    60.0
    65.0
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknow Source)
    at partiel.main(partie1.java:20)
    so i understand that it doesnt change ligne or doesnt do the for correctly but i can't figure where is my mistake.
    thank for your help

    What do the records in the file look like?
    This code:
    for(int i=0;i<15;i++){
        nomEleve=ligneTemp.nextToken();
    System.out.println(nomEleve[i]);
    for(int j=0;j<5;j++){
    notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
    System.out.println(notesEleve[i][j]);
    will call nextToken() on each line 15 + (15 * 5) = 90 times.
    Does each line contain 90 tokens?

  • String and stringtokenizer problem

    Hi,
    String s=new String(null);
    is it possible or not?
    StringTokenizer st=new StringTokenizer(null,",");
    is it possible or not?

    hi sudha,
    when u write
    String s=new String(null); is wrong. Just b'coz the method of String(byte()) that are from java.lang.String will match with your declared method.
    so it will have to clashing ...so u will get ERROR dear.
    Regards
    saM

  • File I/O and StringTokenizer

    Hi
    This may be really simple, but I seem to have problem here. I am reading a txt file using FileReader and I am just printing it out. The txt file has lots of lines. What I want now is to take just the lines which has an = sign on it( there should be only one =) and print just that. This line in the txt file is the form key=value(a hashtable) I need to printout just those lines which are of these form key=value and ignore all the lines. I know I should use the StringTokenizer, but how do I read the.txt file and check if there is any blank line or illegal line and select the line with key=value and print it.
    Please let me know.
    Thanks

    yourStuff() is a snippet that you will change with your source code.
    The regular expression is:
    "^\\w+=\\w+$"
    It means: "from starting data input position (^) followed with one or more char in set [a-zA-Z0-9_] (\\w+), followed with an '=', followed with one or more char (\\w+) till the end of data input ($)".
    It assures no more than one '=' in a line but since you can have blankspaces surrounding this char use that: "^\\w+\\s*=\\s*\\w+$".
    The method "matches()" means "exactly matches" and using anchors: ^ and $, ie; exactly matches from start to end of data input.

  • Problem with stringtokenizer on event handling

    First of all I apologise if its not the proper area.
    I have built a typical gui with netbeans builder.When I double-click a button to switch to source and edit its actionPerformed function the first thing I do is to declare a StringTokenizer variable.I am tottaly sure that I have imported java.util package.So I ask for your help.Whats the deal and I cannot do this declaration?
    thanks in advance!
    EDIT:
    My code
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
       StingTokenizer stok=new StringTokenizer("kjvfw jqwejoiqe ieie9");
    }       Edited by: ultimate_aektzis on Dec 23, 2008 7:14 PM
    Edited by: ultimate_aektzis on Dec 23, 2008 7:16 PM

    Spell StringTokenizer correctly.
    (and it will help if you post the exact error message in the future.)

  • Parsing a string using StringTokenizer

    Hi,
    I want to parse a string such as
    String input = ab{cd}:"abc""de"{
    and the extracted tokens should be as follows
    ab
    cd
    "abc""de"
    As a result, I used the StringTokenizer class with deilmeter {,},:
    StringTokenizer tokenizer = new StringTokenizer(input,"{}:", true);
    In this was, I can separate the tokens and also can get the delimeters. The problem is I don't know how to parse the string that has double quote on it. If a single quote " is taken as a delimeter then
    ", abc, ",", de," all of them will be taken as a separate token. My intention is to get the whole string inside the double quote as a token including the quotes on it. Moreover, if there is any escape character "", it should be also included in the token. Help please.
    Thanks

    A bit of a "sticky tape"-solution...
    import java.util.StringTokenizer;
    public class Test {
        public static void main(String[] args) {
            String input = "ab{cd}:\"abc\"\"de\"";
            StringTokenizer st = new StringTokenizer(input, "{}:", true);
            while(st.hasMoreTokens()) {
            String token = st.nextToken();
            if(token.startsWith("\"") && token.endsWith("\"")) {
            token = token.substring(1,token.length()-1);
                System.out.println(token);
    }

  • Error in StringTokenizer

    I am trying to run this code that I got from a textbook. The only thing that I changed was the name of the file that was to be read in. It was "inventory.dat" and I changed it to "clients.txt".
    The code compiled fine but when I went to run it I got the following error:
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknown Source)
    at CheckInventory.man(CheckInventory.java:34)
    What does this error mean? And why didn't it work? I took it right out of my textbook. Any insight would be appreciated.
    //  CheckInventory.java       Author: Lewis/Loftus
    //  Demonstrates the use of a character file input stream.
    import java.io.*;
    import java.util.StringTokenizer;
    public class CheckInventory
       //  Reads data about a store inventory from an input file,
       //  creating an array of InventoryItem objects, then prints them.
       public static void main (String[] args)
          final int MAX = 100;
          InventoryItem[] items = new InventoryItem[MAX];
          StringTokenizer tokenizer;
          String line, name, file = "clients.txt";
          int units, count = 0;
          float price;
          try
             FileReader fr = new FileReader ("clients.txt");
             BufferedReader inFile = new BufferedReader (fr);
             line = inFile.readLine();
             while (line != null)
                tokenizer = new StringTokenizer (line);
                name = tokenizer.nextToken();
                try
                   units = Integer.parseInt (tokenizer.nextToken());
                   price = Float.parseFloat (tokenizer.nextToken());
                   items[count++] = new InventoryItem (name, units, price);
                catch (NumberFormatException exception)
                   System.out.println ("Error in input. Line ignored:");
                   System.out.println (line);
                line = inFile.readLine();
             inFile.close();
             for (int scan = 0; scan < count; scan++)
                System.out.println (items[scan]);
          catch (FileNotFoundException exception)
             System.out.println ("The file " + file + " was not found.");
          catch (IOException exception)
             System.out.println (exception);
    //  InventoryItem.java       Author: Lewis/Loftus
    //  Represents an item in the inventory.
    import java.text.DecimalFormat;
    public class InventoryItem
       private String name;
       private int units;    // number of available units of this item
       private float price;  // price per unit of this item
       private DecimalFormat fmt;
       //  Sets up this item with the specified information.
       public InventoryItem (String itemName, int numUnits, float cost)
          name = itemName;
          units = numUnits;
          price = cost;
          fmt = new DecimalFormat ("0.##");
       //  Returns information about this item as a string.
       public String toString()
          return name + ":\t" + units + " at " + price + " = " +
                 fmt.format ((units * price));
    }clients.txt
    Widget 14 3.35
    spoke 132 0.32
    wrap 58 1.92
    thing 28 4.17

    when I went to run it I got the following error:
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknown Source)
    at CheckInventory.man(CheckInventory.java:34)
    What does this error mean?It means that when you called nextToken() there weren't any more tokens. In other words the input line didn't contain as many tokens as you expected.

  • Txt file read in- StringTokenizer- Try Block Catch for errors

    Hello
    So I am having a few issues with a school project. First is with my ReadWithScanner. It does not read in the file giving me a NullPointerException error on the line <Scanner in = new>. I have tried a few other read in files and they do not seem to be working.
    I am also stuck on the logic on the try block catch statement. How does a person set up a �custom� try block that looks for errors like the ones below? I have attempted to start in the commented code.
    The text file has to read in 1000 individual lines of code and are separated by �;� and should be separated into tokens with the StringTokenizer class what I attempted to do below also. Both are mere attempts and need help�
    This is some what of the logic I thought of doing
    1.Read the first line in first with the scanner class
    2.use delimiter separated by �;�
    3.Tokenizer the line into separate tokens- invoiceCode, fName, lName�
    4.Check classes- check Name, check Date, checkPrice, checkPrice, checkGenre, checkShippingDate invoiceCode = "Error Code" checkInvoiceCode(String invoiceCode)checkName(String name), checkPrice(String price), checkGenre(String genre)
    5.Apply the regular expressions to each try block statement
    a.Assign a letter to each error for example if invoice was to short it would be assigned a letter A
    b.If invoice does have the right characters it would be assigned B
    c.If name has to few words it would be assigned D
    d.�
    This is an example of a good field from the text file
    XYG726;Smith,Mr. John M.;29.96;comedy;101008;100604
    Not so good line
    Lu15;Will, Mark;50.00;Science;030305;030807
    The file should then be printed out in the program not to a text file. It only needs to print the invoice number and error code letter assignment.
    If you have any questions feel free to let me know. Thanks for all or any help you have to offer.
    Invoice
    Three upper case letters followed by three digits
    Regular Expression "[A-Z]{3}[0-9]{3}"
    Customer Name
    Should be in the form: last name followed by a <,> optional title (Mrs. Mrs�) then first name optional middle initial Titles must be
    So regular expression something like �[a-z][A-Z]+([A-Z]{1}?[a-z][./})+[a-z][A-Z]�
    Sale Price
    Two decimal digits to the left of the decimal point. The price should not have a leading zero.
    Regular Expression [0-9]{2}*./[0-9]
    Genre
    The genre should only contain lowercase letters. Regular expression �[a-z]�
    ShipDate and Order Date-
    Must be standard dates- MMDDYY. The order date and shipping date has to be after today�s date. Regular expression �[0-9]{2}+[0-9]{2}+[0-9]{2}�
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
    private final File fFile;
    public static void main (String args[]){
    Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
    Scanner.processLineByLine();
    public ReadWithScanner(String aFileName){
    fFile = new File(aFileName);
    public final void processLineByLine(){
    try {
    //use a Scanner to get each line
    Scanner scanner = new Scanner(fFile);
    while ( scanner.hasNextLine() ){
    processLine( scanner.nextLine() );
    scanner.close();
    catch (IOException ex){
    protected void processLine(String aLine){
    //use a second scanner again to raed the content of each line
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter(";");
    if (scanner.hasNext() ){
    //read each file?
    String name = scanner.next();
    String value = scanner.next();
    else {
    scanner.close();
    //Token Names that are seperated
    StringTokenizer st;
    String invoiceCode = st.nextToken();
    String fname = st.nextToken();
    String lname = st.nextToken();
    String price = st.nextToken();
    String genre = st.nextToken();
    String orderDate = st.nextToken();
    String shipDate = st.nextToken();
    String invoiceCode;
    invoiceCode = "A" checkInvoiceCode(String invoiceCode);
    Pattern p = Pattern.compile("[a-z]{6}[A-Z]{6}[0-9]{6}");
    Matcher m = p.matcher(invoiceCode);
    p.matcher(invoiceCode);
    if(m.matches()) {
    System.out.println(invoiceCode);
    else {
    System.out.println ("A");
    try
    invoiceCode = Integer.parseInt(String);
    catch (NumberFormatException e)
    { System.out.println ("B"); System.exit(1); }
    */

    I have made a quite a few updates to my code. Please look it over again. I have also made many comments to help with the logic. Once again if you have any questions please feel free to ask. Sorry about not using the tags before- I was no aware of them. Thanks for the advice sabre150.
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
         private final File fFile;
         public static void main (String args[]){
                   //read in text file from directory currently it can not read the file
                  Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
                  //Scans each line of the text in
                  Scanner.processLineByLine();
                //assigns new file name to file
                public ReadWithScanner(String aFileName){
                  fFile = new File(aFileName); 
                public final void processLineByLine(){
                  try {
                    //use a Scanner to get each line from the processLineByLine
                    Scanner scanner = new Scanner(fFile);
                    while ( scanner.hasNextLine() ){
                      processLine( scanner.nextLine() );
                    scanner.close();
                  catch (IOException ex){
                protected void processLine(String aLine){
                  //use a second scanner again to read the content of each line
                   //delmiter should then break each line in the text file into seperate "tokens"
                  Scanner scanner = new Scanner(aLine);
                  scanner.useDelimiter(";");
                  if (scanner.hasNext() ){
                       //reads each line from scanner
                    String name = scanner.next();
                  else {
                  scanner.close();
               /*Convert Tokens from Scanner into String Tokenizer with assigment to each variable
                * I am missing something
                * Need to convert each line read from the scanner (name variable) to the String
                * Tokenizer class
              //Tokens names now assigned a varaible
              StringTokenizer st;
              String invoice = st.nextToken();
              String name = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
          /*If statments (Try Block Statements?) with Regular Expressions
          * This is where I have the most issues on how to set up
          * "custom" try and block errors trying to match what I have
          * in the regular expressions. 
          * I believe try and catch statements
          * make this easier but I have used 'match' and 'pattern' with if
          * statments.  If try block statements are easier please show!
          * Regular Expressions may not be correct either
           invoice = checkInvoiceCode(invoice);
           //Defined cerita for Inovice are:
           //Error A = Invoice code is too short  
           //Error B = Invoice code does not have the right characters 
           //Error C = Invoice code digits are all zero
           //Checks for error A
           //Has at least six characters
            Pattern invoiceShort = Pattern.compile("{6}");
            Matcher shortInvoice = invoiceShort.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);      
            else {
                 System.out.println ("A");
            //Checks for error B
            //3 Upper Case Letters followed by three numbers,
            Pattern rightChar = Pattern.compile("[A-Z]{3}[0-9]^0{3}");
            Matcher charRight = rightChar.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);
            else {
                     System.out.println ("B");
            //Checks for error C
            //Where the last three digits are not all zeros
            Pattern notZero = Pattern.compile("*{3}^0{3}");
            Matcher ZeroNot = notZero.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice); 
                 else {
                     System.out.println ("C");
         //name = checkFullName(name);
         //Error D = Name field has fewer than two words
         //Error E = Name field has more than four words
         //Error F = Name field has no comma
         //Error G = Name field has a bad title 
         //Error H = Name field has a bad initial 
        /*Have a lot more to do...
        * Still need to go through the same if statement or Try Block statements with this data:
        *      String fname = st.nextToken();
              String lname = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
        * But for now I would like to see an example of an if statement I could use
        * (if mine is even right) or catch statement- the rest of the project we look
        * for similar certia as defined in the reg exp for invoice
         /*Writes to Report in the Console
         * Prints data into two columns:
         * Invoice Code and Error Type
         //Prints both column Headings
         private void columnHeadings ()
         System.out.println (padL("",5) +
         padL("Invoice",20) +padL("",20)+
         padL("Error Code",40));
         //movie is the name of the text file
         private void printMovie(Movie aReport) {
         System.out.println(aReport.getInvoiceCode()+"\t"+
               aReport.getErrorType()+"\t");
      *This method pads the string start to the length newLength leaving the
      *string left justified and returning the result.
      private String padL (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result += " ";
         return result;
      } // end padL
       * This method pads the string start to the length newLength leaving the
       * string right justified and returning the result.
      private String padR (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result = " " + result;
         return result;
    // end padRThanks a lot.

  • How to Exclude Java Reserved Words Using StringTokenizer

    Hi, i'm trying to exclude identifiers and java reserved words using StringTokenizer from an input file outputting the remaining words alphabetically ordered with the line, on witch they occur, in front of the word.
    So far my code does all that, except exclude those words. I'm kind on a dead end... Any suggestions?
    The code:
    public class Interpreter{
        /* Uses a Binary Search Tree      */
        public static void main(String args[ ]) {
            String path = null;
            for (int j = 0; j < args.length; j++) {
                try {
                    // Step 1, read the input file
                    path   = args[j];
                    FileReader input = new FileReader(args[j]);
                    BufferedReader br = new BufferedReader(input);
                    String line;
                    int count = 1;
                    String word;
                    // Step 2, create an empty Tree
                    BST tree = new BST();
                    while((line = br.readLine())!=null){
                        StringTokenizer str = new StringTokenizer(line);
                        while (str.hasMoreTokens()){
                            word = str.nextToken();
                            tree.insert(word,count);
                        count++;
                    // We're done, print out contents of Tree!
                    tree.print();
                    // Error Handling
                    //check for IO problem with bad file
                } catch (IOException e) {
                    System.out.println("There was a problem with the filename you entered.");
                    //check for no filename entered at command prompt
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Please include a filename when running this program.");
    }Edited by: Redol on Dec 12, 2007 8:32 PM
    Edited by: Redol on Dec 12, 2007 8:33 PM

    use split instead of tokenizer.
    public String[] splitString( String line, String delim )
        String[] tokens = null;
        if( line != null )
            tokens = line.split( delim );
        return tokens;
    }

Maybe you are looking for

  • How to hide photo albums?

    Hi, Is there any app to hide the photo albums I uploaded from my pc? I tried to look for such apps but they are not what I want. They make folders in that particular app and then hides them. What I want is to hide entire photo albums, for example I u

  • Can anyone tell me how to get Java installed?

    I have tried to install java several times and it says it is installed yet I cannot find it anywhere on my Mac.

  • G5 dual 1.8ghz

    Hello, need to know if i install a processor from a G5 dual 2.0ghz or above into my dual 1.8ghz if it will work correctly. Not to compter savvy trying to get more processing power for my Pro Tools Le rig. Also, any one who knows Pro Tools is there a

  • How to Uninstall iTunes (for installing it latter)

    How to Uninstall iTunes from my Mac (for installing it latter)

  • Device and app sharing separate apple I.d's

    Hello I am new two apple gadgets but am getting hooked on them. My situation is I have iPod and another family member has one. I put iTunes on old p.c. And syncing between both was fine. I got new p.c. No iTunes on it yet. Now it may get a little com