StringTokenizer help

i have this code to read a text file and put it's contents in a string and then use the string tokenizer to separate it
public static void readTF()
String s = TextIO.readTextFile();
StringTokenizer sToken = new StringTokenizer(s);
javax.swing.JOptionPane.showMessageDialog(null, "" + sToken);
but i get the error message, "cannot resolve symbol - class StringTokenizer"?
i have declared the class at the start of the file as "import java.util.StringTokenizer.*;"
any ideas?

"import java.util.StringTokenizer.*;"Heheh, not quite. The package is java.util, so you can import all of that with import java.util.*; Or you can import 1 specific class (StringTokenizer) with import java.util.StringTokenizer; But importing java.util.StringTokenizer.*; means nothing.
And change this:
> javax.swing.JOptionPane.showMessageDialog(null, "" + sToken);to this:
javax.swing.JOptionPane.showMessageDialog(null, sToken.nextToken());Cheers,
Radish21

Similar Messages

  • Some StringTokenizer help

    Hi, I have a code that reads in a text file, filter out the field and prints out the integer next to the " : " sign. For example, my text file is in the form of
    a : 1
    b : 2
    c : 3
    Special : 99
    a1 : 2
    b1 : 3
    c1 : 4
    Special : 100
    The printing will pause each time it encounters the "--" sign (to signify 1 block of message). How do I modify the code such that it will store up the value of "Special" to be used later? And is there a need to manually clear the value of "Special" when the next message block is printed (when "Special" takes the value of 100?)
    The original code is :
    import java.io.*;
    import java.util.*;
    public class ReadFileTest
    public static void main (String[] args)
         byte bytes[] = new byte[100];
         int  index   = 0;
         try
              FileReader     file = new FileReader("data.txt");
              BufferedReader buff = new BufferedReader(file);
              String         line  = null;
              while ((line = buff.readLine()) != null)
                   if (line.trim().equals("--"))
                        System.out.print("Enter to continue");
                        System.in.skip(System.in.available());
                        System.in.read();
                        System.out.print("");
                   else if (line.trim().equals(""))
                   else
                        StringTokenizer st = new StringTokenizer(line,":");
                        if (st.countTokens() != 2)
                             System.out.println("Error:  "+line);
                        else
                             st.nextToken();
                             try
                                  int i = Integer.parseInt(st.nextToken().trim()); //output as a byte array
                                  bytes[index++] = (byte)i;
                                  System.out.println(""+i);
                                  //System.out.println(""+Integer.parseInt(st.nextToken().trim()));
                             catch(NumberFormatException e){}
              buff.close();
         catch(IOException e)
         System.out.println("IO Error");
    }Thanks a million for the help anyone can provide.
    [code courtesy of Noah. Thanks]

    import java.io.*;
    import java.util.*;
    public class ReadFile
    public static void main (String[] args)
         byte bytes[] = new byte[100];
         int  index   = 0;
         int  special = -1;
         try
              FileReader     file = new FileReader("f.txt");
              BufferedReader buff = new BufferedReader(file);
              String         line  = null;
              while ((line = buff.readLine()) != null)
                   if (line.trim().equals("--"))
                        System.out.print("Enter to continue");
                        System.in.skip(System.in.available());
                        System.in.read();
                        System.out.print("");
                   else
                        StringTokenizer st = new StringTokenizer(line,":");
                        if (st.countTokens() != 2)
                             System.out.println("Error:  "+line);
                        else
                             String s = st.nextToken();
                             try
                                  int i = Integer.parseInt(st.nextToken().trim());
                                  bytes[index++] = (byte)i;
                                  if (s.equals("Special")) special = i;
                                  System.out.println(""+i);
                             catch(NumberFormatException e){}
              buff.close();
         catch(IOException e)
              System.out.println("IO Error");
    Noah

  • School Project Help (StringTokenizer/JOptionPane/etc)

    Hey again guys,
    I've had great help in the past here and im hoping you guys will be able to aid me again.
    This is very similar to my last project where I created a program, thank God, with help from you guys and information online and in the textbook, using the JOptionPane to ask for some information, perform some calculations, a basic thing with the mask of a Photo Printing Shop.
    Now I am trying to take all that information and ask for it in ONE JOptionPane window where the 'customer' will enter information seperated by spaces.
    Example:
    I know how to bring up the Joptionpane to display something like:
    Please enter your customer information in this order, followed by spaces,
    First Name
    Last Name
    Phone number
    Now Im trying to get them to enter this information like this:
    Homer Simpson 5551234321
    What code is used to have them put this information in with spaces to separate each piece of information?
    Thanks again everyone.

    To help you guys get an idea for the project I am trying to do, here are the instructions I was given:
    Assignment
    *1.* You are to write a simple program with two classes. One controller class and a
    class to hold your object definition. (Similar to what we used in class)
    *2.* Read in the following from the JOptionPane input window, All data to be entered
    in one line separated by spaces. After the information is read use the
    StringTokenizer to break it into variables:
    a. Name of customer (example: Homer Simpson)
    b. Customer Phone Number (example: 9093873744)
    c. Number of rolls of film to be developed (example: 5)
    d. Number of 4 x 6 prints to be made of each film. (example 8)
    *3.* Number of Exposures is not entered by user instead it?s a CONSTANT value is 1
    *4.* Make sure the following is entered correctly, use Try/Catch validation otherwise
    display an error message and close the program:
    a. The name of the customer is not blank
    b. The phone number of the customer is not blank and doesn?t exceed 10
    characters and is an integer with positive number only
    c. The number of rolls is between 1 and 100 and is an positive integer
    d. The number of prints can only be (1,2,8,10, 25,30,50), positive integer
    *5.* Compute the cost for making pictures using the price of $5.19 for development of
    a roll of film and the price of $0.15 per picture.
    *6.* Use the following to perform the calculations:
    a. Cost for development = number of rolls * development cost
    b. Cost for printing = number of rolls * number of prints * number of
    exposures * printing cost
    c. Subtotal = Cost for development + Cost for printing
    d. Tax = Subtotal * Tax rate
    e. Total = Subtotal + Tax

  • Help: Problems with StringTokenizer

    Hello.
    I try to use the StringTokenizer class for divide a String into tokens, but I want to use a String like "," (including the double quotation marks), but the StringTokenizer not behaves like I expected, it thinks that the quotation marks and the comma are independent separators.
    I construct my StringTokenizer object in this way
    StringTokenizer st = new StringTokenizer( stringvariable, "\",\"");
    There is another possibility to StringTokenizer behaves like I expect?
    There is another class to help me?
    Thanks

    StringTokenizer st = new StringTokenizer(
    stringvariable, "\",\"");
    Try to change it to:StiringTokenizer st = new StringTokenizer(str, "\",");

  • Help on StringTokenizer

    Hi All,
    I am developing a program to read a logfile and display the selected data in different windows.
    In one window I have to add a series of buttons (A..Z) and when I click a button it should display data starting with that letter. for e.g.
    0.01 0.01 191650 5 | ae United Arab Emirates
    0.01 0.01 146570 8 | am Armenia
    0.04 0.04 994907 36 | ar Argentina
    0.23 0.21 5282499 212 | at Austria
    1.89 2.11 51905657 1729 | au Australia
    0.60 0.54 13423956 545 | be Belgium
    0.01 0.01 316190 6 | bh Bahrain
    0.00 0.00 7397 2 | bn Brunei Darussalam
    When I click button A, it should display the data for Armenia, Argentina so on.
    I managed to add a series of buttons and attach action listeners to them but I cannot figure out a method to go through the logfile and compare the country names starting for the relevant button.
    Could anyone suggest something for this please? (I use the stringtokenizer to tokenize the string)
    Many thanks in advance!
    Happy Prince

    Yeah, you can't do it that way...
    What I posted before with the StringTokenizer will tokenize your log (based on what you posted, at least) and create objects based on some class you could write to hold the data. That was intented to go with the first code I posted with the add/get methods with the Map of List or objects thing. That is a more object oriented way to handle the data.
    First... if you add an actionListener like you are, you don't need to check the source, cuz it's really creating separate little ActionListener objects for each button. No 2 will share the same one. So you can add actionListeners like this:
       for (int i=0; i<clntDomain.btnLetters.length; i++) // better to use the array length
    clntDomain.btnLetters[i].addActionListener( new ActionListener() //adding action listeners to buttons
    public void actionPerformed(ActionEvent ae)
    // do action code
    } //end actionPerformed()
    }); //end inner class
    } //end for
    And if you did it my way with the Map/List/custom object, in the action performed method you'd call
    List list = getObject(ae.getActionCommand()); // assuming the action command was the letter for the buttonSecond, you don't want to read and write into the action listener like that cuz you don't really know (generally) how many of each letter. So you are better off reading the entire text file at one time first. I would still recomment using a map, but if you just want the raw lines...
    I think you can rewrite the whole method like this:
    protected HashMap map = new HashMap();
    private void loadClientDomain()
       String lineData;
       final ClientDomain clntDomain = new ClientDomain("Total Transfers by Client Domain");
       clntDomain.setVisible(true);
       try
          final BufferedReader bufferLog = new BufferedReader(new InputStreamReader(logFile.openStream()));
          lineData = bufferLog.readLine();
          while(!lineData.startsWith("%Reqs %Byte  Bytes Sent  Requests   Domain")) //reads upto this line
             lineData = bufferLog.readLine();
          } //end while
          // I'm assuming the lines in the log are already alphabetical by country code...
          while((lineData = bufferLog.readLine()) != null) {
             int pipe = lineData.indexOf("| ");
             String c = lineData.substring(pipe+2, pipe+3); // the letter...
             String str = (String)map.get(c);
             if(str == null) {
                str = lineData + "\n";  // set first if null
             } else {
                str += lineData + "\n"; // else, just append
             map.put(c, str); // replace old string
          for (int i=0; i<clntDomain.btnLetters.length; i++) // better to use the array length
    clntDomain.btnLetters[i].addActionListener( new ActionListener() //adding action listeners to buttons
    public void actionPerformed(ActionEvent ae)
    String str = (String)map.get(ae.getActionCommand());
    if(str == null) {
    str = "";
    field.setText(str);
    } //end actionPerformed()
    }); //end inner class
    } //end for
    } // end try
    catch(Exception ex)
    System.out.println("Error" + ex);
    } //end catch
    } //end loadClientDomain();
    Anyway, these are separate blocks. You would want to completely read the log in one step, then set up the

  • Dynamic strings from stringtokenizer..any help please?

    basically u hav a jsp search page...and on the page is a textbox where a user can type in information they want to match.
    now they hav to type it in a way so that the criteria is separated by 'AND' i.e. search greg AND ching
    and this should be taken from the textbox...passed into a process javabean...broken up into separate strings
    i.e.
    String one = greg
    String two = ching
    and then i will input this into an sql statement to search the database.
    my question is what i have done so far is this...
    String searchCriteria = request.getParameter("searchArea");
    String target = "";
    String nextTarget = "";
    StringTokenizer token = new StringTokenizer(searchCriteria,"AND");
    while(token.hasMoreTokens()) {
    target = token.nextToken();
    out.println(target);
    which basically gets the data from the textbox...separates the criteria when it sees AND and then saves it in a string called target
    so at the moment the String target will be = greg ching
    is there anyway i can separate the criteria via AND (like above) and save it in separate String variables rather than just one?
    bare in mind that if they enter 3 criteria....like greg AND ching AND struggling then it should make 3 strings and save it in them respectively
    thanks a lot...im sure its a minor thing butu see im really really thick :o(

    Sure... a couple of ways you could do it..
    StringTokenizer token = new StringTokenizer(searchCriteria,"AND");
    String[] criteria = new String[token.countTokens()];
    int j=0;
    while(token.hasMoreTokens())
      criteria[j] = token.nextToken();
    /* OR  */
    StringTokenizer token = new StringTokenizer(searchCriteria,"AND");
    ArrayList criteria = new ArrayList();
    while(token.hasMoreTokens())
      criteria.add(token.nextToken());

  • Help with ArrayList...

    Hi Everyone:
    I have this java program that I'm doing for school and I need a little bit of insite on how to do certain things. Basically what I did was I read a text file into the program. Once I tokenized the text(by line), I created another object(we'll call it Throttle) and passed the values that was tokenized, then I stored the object(Throttle) into ArrayList. Now, my question is how to I access the object(Throttle) from the ArrayList and use the object's(Throttle) methods? Here's the code that I have currently:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class Project1 extends JFrame
    private JButton numOfThrottles, shiftThrottle, createThrottle, quit;
    private JPanel panel;
    private FileReader fr;
    private BufferedReader br;
    private FileWriter fw;
    private int tempTop;
    private int whatToShift;
    private int tempPosition;
    private ArrayList arrThrottles = new ArrayList();
    private String line;
    private Throttle myThrottle = null, daThrottle;
    private StringTokenizer st;
    public Project1()
    super ("Throttles - by Joe Munoz");
    panel = new JPanel();
    setContentPane(panel);
    panel.setLayout(null);
    //**button stuff
    numOfThrottles = new JButton("Number of Throttles");
    shiftThrottle = new JButton("Shift a Throttle");
    createThrottle = new JButton("Create New Throttle");
    quit = new JButton("Quit");
    panel.add(numOfThrottles);
    panel.add(shiftThrottle);
    panel.add(createThrottle);
    panel.add(quit);
    numOfThrottles.setBounds(5,7,150,25);
    shiftThrottle.setBounds(5,30,150,25);
    createThrottle.setBounds(5,50,150,25);
    quit.setBounds(5,70,150,25);
    numOfThrottles.addActionListener(new ClickDetector());
    shiftThrottle.addActionListener(new ClickDetector());
    createThrottle.addActionListener(new ClickDetector());
    quit.addActionListener(new ClickDetector());
    //window stuff
    setSize(170,135);
    show();
    try
    br = new BufferedReader(new FileReader("C:\\Storage.txt"));
    catch (FileNotFoundException ex)
    System.out.println ("File Not Found!");
    try
    line = br.readLine();
    while (line != null)
    st = new StringTokenizer(line, " ");
    tempTop = Integer.parseInt(st.nextToken());
    tempPosition = Integer.parseInt(st.nextToken());
    myThrottle = new Throttle(tempTop, tempPosition);
    arrThrottles.add(myThrottle);
    line = br.readLine();
    catch(Exception e)
    System.out.println("IO Exception!!!");
    System.exit(0);
    private class ClickDetector implements ActionListener
    public void actionPerformed(ActionEvent event)
    try
    if (event.getSource() == numOfThrottles)
    JOptionPane.showMessageDialog(null, "Number of Throttles is..." + myThrottle.getNumOfThrottles());
    if (event.getSource() == shiftThrottle)
    String shift = JOptionPane.showInputDialog("Please Choose a Throttle from 0 to " + (arrThrottles.size() - 1));
    whatToShift = Integer.parseInt(shift);
    System.out.println ("whatToShift = " + whatToShift);
    // Need help here
    if (event.getSource() == createThrottle)
    String inTop = JOptionPane.showInputDialog("Please Enter Top");
    tempTop = Integer.parseInt(inTop);
    String inPosition = JOptionPane.showInputDialog("Please Enter Position");
    tempPosition = Integer.parseInt(inPosition);
    myThrottle = new Throttle(tempTop, tempPosition);
    arrThrottles.add(myThrottle);
    JOptionPane.showMessageDialog(null, "The Throttle has been created");
    if (event.getSource() == quit)
    System.out.println ("you clicked quit");
    catch (Exception e)
    JOptionPane.showMessageDialog(null, "No Numbers inputted!");
    Any insite/suggestions on what to do? Thank You.
    Joe

    Hi,
    I have a question addition to this same question.
    If you have an object and there are 10 different objects with in the object ..
    tempTop = Integer.parseInt(st.nextToken());
    tempPosition = Integer.parseInt(st.nextToken());
    tempBottom = 10;
    Is this how you access( from the same example) each object value
    strTop= (Throttle)arrThrottles.get(i).tempTop;
    strPos= (Throttle)arrThrottles.get(i).tempPosition;
    strB= (Throttle)arrThrottles.get(i).tempBottom;
    ----I AM USING ARRAYS in a JAVABEAN
    Class test {
    public objectTEMP t[] = null;
    public void initialize(val1,al2) {
         t = redim(t,10,false); //To set the length of the array to 10
    public class T {
    String s1 = null;
    String s2 = null;
    int i1 = null;
    public void setS1(String inVal) {
              s1=inVal;
    public void setS2(String inVal) {
         s2=inVal;
    public void setI1(int inVal) {
         i1=inVal;
    public String getS1() {
              return s1;
    public String getS2() {
              return s2;
    public String getI1() {
              return i1;
    for (int i=0; i<t.length;i++) {
    System.out.println("t"+i+t.getS1());
    t.setS1("SOMESTRING");
    System.out.println("t"+i+t.getS1());
    Any use the setter and getter method from JSP to update or get the information.
    I want to change this to ArrayList as they are fast and they have resizing ability.
    How to I implement this in ARRAYLIST.
    Thanks a bunch

  • Print to screen OR file problem, need help please.

    Hiyo!, im doing a certain program the way to Uni wants me to do it so im using a textFile jar file for all the reading writing etc, i know its not standard java but thats not what im having trouble with.
    Im trying to make a prog that will print its results to screen if the only augument on the command line is the file to read from eg.( java ProgramThree input.txt ).
    but if two arguments are written on the command line eg.( java ProgramThree input.txt output.txt ) then it
    will print the results to the file (output.txt) and not display to screen.
    I know that its just that ive messed up a couple of the "args.length" statments in main() , but my brain gets confused easy :[
    Any help would be sweet. Thanks.
    class ProgramThree
            public static String calc(String line)
                String type[] = {"Valid Isosceles","Valid Equilateral","Valid Scalene","Invalid"};
                String result = null;
              int s1 = 0;
              int s2 = 0;
              int s3 = 0;
              try
                   StringTokenizer st = new StringTokenizer(line);
                   s1 = Integer.parseInt(st.nextToken());
                   s2 = Integer.parseInt(st.nextToken());
                   s3 = Integer.parseInt(st.nextToken());
              catch (Exception e) {e.printStackTrace();}
              if ((s1+s2>s3)&&(s1+s3>s2)&&(s2+s3>s1))
                   if((s1==s2)||(s1==s3)||(s2==s3))
                        if((s1==s2)&&(s1==s3))
                             result = type[1];
                        else
                             result = type[0];
                   else
                        result = type[2];
              else
                   result = type[3];
              return result;
            public static void printScreen(String result)
              System.out.println("\nTriangle is: " +result+ "\n");
            public static void main(String args[])
              String line = null;
              String result = null;
                    if(args.length > 2)
                      System.out.println("Too many Filenames Given!");
                      System.exit(1);
                    textFile inFile = new textFile(args[0], 'r');
                    textFile outFile = new textFile(args[1], 'a');
              while(!inFile.EOF())
                   line = inFile.readLine();
                   if(line == null)
                        break;
                   result = calc(line);
                   if(args.length == 0)
                        printScreen(result);
                   else
                                 outFile.writeLine(result);
                        System.out.println("\nResults written to file.");
              inFile.closeFile();
              outFile.closeFile();
              return;
    }

    Thanks for your reply neil!
    But im not to sure how I would impliment your code into my program :0
    The code that I posted before is throwing an arrayOutOfBounds exception at the line
    inFile = new textFile(args[0], 'r');
    outFile = new textFile(args[1], 'a'); <-----------Here
    This happens if I enter none or one auguments on the command line :/
    But if I enter two auguments it works fine and writes to file..
    I know its because when there is one augument on the command line (or none at all) it opens to outFile for nothing, because its printing to screen?
    The thing is i dont know how to fix this :[
    -thanks

  • 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);

  • 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?

  • Can you help me with these exceptions??

    Hi guys,
    from sunday i try to eliminate these exceptions from my jsf application and i've lost any confidence in my possibility to realize it.....
    It's surely a simple problem but i'm a newbie of jsf and java.
    These are the exadel msg
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: #{MyBean.retrieveblob}: javax.faces.el.EvaluationException: java.lang.NullPointerException
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:209)
         org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)
    root cause
    javax.faces.FacesException: #{MyBean.retrieveblob}: javax.faces.el.EvaluationException: java.lang.NullPointerException
         com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:78)
         javax.faces.component.UICommand.broadcast(UICommand.java:312)
         javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:267)
         javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:381)
         com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:75)
         com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
         org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.0.28 logs.
    ant these are the files
    MyBean.java
    package giu;
    import org.apache.myfaces.custom.fileupload.UploadedFile;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringTokenizer;
    import java.util.Vector;
    public class MyBean {
         private UploadedFile myFile;
         private String geneid=null;
        private int row=0;
        private int numberOfNumericColumns=0;
        private int col=0;
        String[]intest=null;
        private ArrayList rows = new ArrayList();
        Head h;
        byte middlerow=' ';
        byte endrow=';';
        byte[] data=null;
        Vector temp=new Vector(100000);
        String g=null;
        Riga r;
        Double val[];
        private String[] arraylinee;
        public boolean insRighe(Riga nuovo){
               return rows.add(nuovo);
        public List stampaRows(){
             return rows;}
        public Head stampaHead(){
             return h;}
        public byte[] getdata(){
             return data;
        public UploadedFile getMyFile() {
            return myFile;
        public void setMyFile(UploadedFile myFile) {
            this.myFile = myFile;
        public int getcol(){
             return col;
        public void setcol(int col){
             this.col=col;
        public int getrow(){
             return row;
        public void setrow(int row){
             this.row=row;
        public String[] getarraylinee(){
             return arraylinee;
        public void setarraylinee(String[] arraylinee){
             this.arraylinee=arraylinee;
    public String retrieveblob(){
              Database2 db = new Database2("nomeDB","root","shevagol");     
              try
              Connection dbo=db.getConnection();
              System.out.println("eccezione buona2");
                   System.out.println("eccezione buona2,5");
                   Statement st = dbo.createStatement();
                   System.out.println("eccezione buona3");
                   ResultSet rs;
                   rs = st.executeQuery("SELECT Data FROM tbl WHERE Nome='16'");
                   rs.first();
                   Blob blob = rs.getBlob("Data");
                   byte[] read = blob.getBytes(1, (int) blob.length());
                   st.close();
                   String lettura=new String(read);
                   String[] arraylinee=lettura.split(";");
                   /*for (int i = 0; i < arraylinee.length; i++) {
                     System.out.println(arraylinee);
              catch(SQLException e)
                   System.out.println("Si � verificato il seguente errore: " + e.getMessage());
                   e.printStackTrace();
              return "retrOk";
    This is my result.jsp page
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ page import="giu.MyBean" %>
    <%-- Instantiate class --%>
    <jsp:useBean id="myBean" class="giu.MyBean" scope="request"/>
    <html>
         <head>
              <title></title>
         </head>
         <body>
              <f:view>
                   <c:forEach items="${myBean.arraylinee}" var="linea" >
    <tr>
    <td>
    <c:out value="${linea}" />
    </td>
    </tr>
    </c:forEach>
              </f:view>
         </body>     
    </html>
    and these are web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
         <context-param>
              <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
              <param-value>client</param-value>
         </context-param>
         <filter>
              <filter-name>ExtensionsFilter</filter-name>
              <filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
              <init-param>
                   <param-name>uploadMaxFileSize</param-name>
                   <param-value>100m</param-value>
              </init-param>
              <init-param>
                   <param-name>uploadThresholdSize</param-name>
                   <param-value>100k</param-value>
              </init-param>
         </filter>
         <filter-mapping>
              <filter-name>ExtensionsFilter</filter-name>
              <servlet-name>FacesServlet</servlet-name>
         </filter-mapping>
         <servlet>
              <servlet-name>FacesServlet</servlet-name>
              <servlet-class>
              javax.faces.webapp.FacesServlet</servlet-class>
              <load-on-startup>1</load-on-startup>
         </servlet>
         <servlet-mapping>
              <servlet-name>FacesServlet</servlet-name>
              <url-pattern>/faces/*</url-pattern>
         </servlet-mapping>
         <servlet-mapping>
              <servlet-name>FacesServlet</servlet-name>
              <url-pattern>*.faces</url-pattern>
         </servlet-mapping>
         <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
         </welcome-file-list>
    </web-app>
    and faces-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
                                  "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
    <faces-config>
    <managed-bean>
      <managed-bean-name>MyBean</managed-bean-name>
      <managed-bean-class>giu.MyBean</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
      <from-view-id>/pages/MyForm.jsp</from-view-id>
      <navigation-case>
       <from-outcome>success</from-outcome>
       <to-view-id>/pages/MyResult.jsp</to-view-id>
      </navigation-case>
    </navigation-rule>
    <navigation-rule>
      <from-view-id>/pages/Login.jsp</from-view-id>
      <navigation-case>
       <from-outcome>Ok</from-outcome>
       <to-view-id>/pages/Menu.jsp</to-view-id>
      </navigation-case>
    </navigation-rule>
    <navigation-rule>
      <from-view-id>/pages/Menu.jsp</from-view-id>
      <navigation-case>
       <from-outcome>upload</from-outcome>
       <to-view-id>/pages/MyForm.jsp</to-view-id>
      </navigation-case>
      <navigation-case>
       <from-outcome>admin</from-outcome>
       <to-view-id>/pages/UserForm.jsp</to-view-id>
      </navigation-case>
      <navigation-case>
       <from-outcome>view</from-outcome>
       <to-view-id>/pages/ViewForm.jsp</to-view-id>
      </navigation-case>
      <navigation-case>
       <from-outcome>register</from-outcome>
       <to-view-id>/pages/Register.jsp</to-view-id>
      </navigation-case>
    </navigation-rule>
    <navigation-rule>
      <from-view-id>/pages/ViewForm.jsp</from-view-id>
      <navigation-case>
       <from-outcome>Result</from-outcome>
       <to-view-id>/pages/Result.jsp</to-view-id>
      </navigation-case>
    </navigation-rule>
    </faces-config>I hope someone can helps me...............
    P.S.
    Can someone says me a good program to debug my applications...?
    I try with exadel but i find it bit intuitive....

    I don't know JSF, but it appears you haven't included part of your application - the one causing the error with the line: #{MyBean.retrieveblob}
    I would assume the error is that you instantiate the bean with the name "myBean" (<jsp:useBean id="myBean" class="giu.MyBean" scope="request"/>) then refer to it as "MyBean". Java is case sensitive.

  • Need help with an assignment

    first of all, who has heard of the game called zuul? It is a very boring text based game I am currently having the pleasure of improving.
    Basically, you are in a room, that is connected to a bunch of other rooms and depending on the room you are in, you have different exists and different items in the room.
    The goal is to navigate through the collection of Rooms and there is no real win condition, It is more for learning then for actually playing.
    You navigate by a series of commands such as: go (direction)( as in "direction of exit", NSEW), quit, a few other odd bits.
    ex: go south, quit, go west etc
    The game has several classes: Game, Command, CommandWords, Item, Parser, Room.
    Obviously Game is the main central head conch, (it is not the super class.)
    Game makes use of Item, Room, Parser, and Command.
    Item is the class that deals with the number of items in the Room.
    Room is the class that deals with the rooms the player will navigate to and from.
    Command reads in the commands such as "go-(direction)" or "quit".
    Parser makes everybody understand each other by using both Command and CommandWords.
    CommandWords is a list of commands such as "go", "quit" etc.
    The problem I am having right now is to allow a player to move through the rooms while holding a certain item. The item has to come from the rooms and the player should be able to drop it.
    So I have to add two new commands: take and drop. The problem is that I have been asked to do this without creating a new class. Otherwise I would have just created class Player and be done with it. So I am trying to figure out whose responsibility should it be to take care of the take and drop command. I have done some preliminary work in class Game, it is the take(Command command) and drop() methods.
    I have also a few questions concerning other aspects of the project, I have listed their locations here:
    1. The take() method in class Game, the for-each loop, a complier error with ArrayList
    2. class Parser, a general question about the string tokenzier
    If you want to see how the game is suppose to run, just comment out the bodies of take() and drop(). Not the declaration. Everything else works.
    I shall now provide the code to all classes. I wish there were an option to upload a zip file, then you don't have to read through all the codes and copy&paste all the codes. The complier I am using is BlueJ. And the SDK version is 1.6. With the exception of class Game, everything else can be assumed to be error free.
    Thank you for your time,
    Davy
    class Game
    import java.util.*;
    *  This class is the main class of the "World of Zuul" application.
    *  "World of Zuul" is a very simple, text based adventure game.  Users
    *  can walk around some scenery. That's all. It should really be extended
    *  to make it more interesting!
    *  To play this game, create an instance of this class and call the "play"
    *  method.
    *  This main class creates and initialises all the others: it creates all
    *  rooms, creates the parser and starts the game.  It also evaluates and
    *  executes the commands that the parser returns.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    public class Game
        private Parser parser;
        private Room currentRoom;
        private Room previousRoom;
        private Stack<Room> previousRooms;
         * Create the game and initialise its internal map.
        public Game()
            createRooms();
            parser = new Parser();
         * Create all the rooms and link their exits together.
        private void createRooms()
            Room outside, theatre, pub, lab, office;
            // create the rooms
            outside = new Room("outside the main entrance of the university");
            theatre = new Room("in a lecture theatre");
            pub = new Room("in the campus pub");
            lab = new Room("in a computing lab");
            office = new Room("in the computing admin office");
            // create some items
            Item desk, chair, beer, podium, tree;
            desk = new Item("desk", "student desk",10);
            chair = new Item("chair", "student chair",5);
            beer = new Item("beer", "glass of beer", 0.5);
            podium = new Item("podium", "lecture podium", 100);
            tree = new Item("tree", "a tree", 500.5);
            // put items in some of the rooms
            outside.addItem(tree);
            theatre.addItem(desk);
            theatre.addItem(chair);
            theatre.addItem(podium);
            pub.addItem(beer);
            pub.addItem(beer);
            office.addItem(desk);
            lab.addItem(chair);
            lab.addItem(beer);
            // initialise room exits
            outside.setExit("east", theatre);
            outside.setExit("south", lab);
            outside.setExit("west", pub);
            theatre.setExit("west", outside);
            pub.setExit("east", outside);
            lab.setExit("north", outside);
            lab.setExit("east", office);
            office.setExit("west", lab);
            currentRoom = outside;  // start game outside
            previousRooms = new Stack<Room>(); // no rooms on the stack
            previousRoom = null;
         *  Main play routine.  Loops until end of play.
        public void play()
            printWelcome();
            // Enter the main command loop.  Here we repeatedly read commands and
            // execute them until the game is over.
            boolean finished = false;
            while (! finished) {
                Command command = parser.getCommand();
                finished = processCommand(command);
            System.out.println("Thank you for playing.  Good bye.");
         * Print out the opening message for the player.
        private void printWelcome()
            System.out.println();
            System.out.println("Welcome to the World of Zuul!");
            System.out.println("World of Zuul is a new, incredibly boring adventure game.");
            System.out.println("Type 'help' if you need help.");
            System.out.println();
            System.out.println(currentRoom.getLongDescription());
         * Given a command, process (that is: execute) the command.
         * @param command The command to be processed.
         * @return true If the command ends the game, false otherwise.
        private boolean processCommand(Command command)
            boolean wantToQuit = false;
            if(command.isUnknown()) {
                System.out.println("I don't know what you mean...");
                return false;
            String commandWord = command.getCommandWord();
            if (commandWord.equals("help")) {
                printHelp();
            else if (commandWord.equals("go")) {
                goRoom(command);
            else if (commandWord.equals("look")) {
                look(command);
            else if (commandWord.equals("eat")) {
                eat(command);
            else if (commandWord.equals("back")) {
                back(command);
            else if (commandWord.equals("stackBack")) {
                stackBack(command);
            else if (commandWord.equals("take")){
                take(command);
            else if (commandWord.equals("drop")) {
                drop(command);
            else if (commandWord.equals("quit")) {
                wantToQuit = quit(command);
            // else command not recognised.
            return wantToQuit;
        // implementations of user commands:
         * Print out some help information.
         * Here we print some stupid, cryptic message and a list of the
         * command words.
        private void printHelp()
            System.out.println("You are lost. You are alone. You wander");
            System.out.println("around at the university.");
            System.out.println();
            System.out.println("Your command words are:");
            System.out.println(parser.getCommands());
         * Try to go to one direction. If there is an exit, enter the new
         * room, otherwise print an error message.
         * @param command The command entered.
        private void goRoom(Command command)
            if(!command.hasSecondWord()) {
                // if there is no second word, we don't know where to go...
                System.out.println("Go where?");
                return;
            String direction = command.getSecondWord();
            // Try to leave current room.
            Room nextRoom = currentRoom.getExit(direction);
            if (nextRoom == null) {
                System.out.println("There is no door!");
            else {
                previousRooms.push(currentRoom);
                previousRoom = currentRoom;
                currentRoom = nextRoom;
                System.out.println(currentRoom.getLongDescription());
         * "Look" was entered.
         * @param command The command entered.
        private void look(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Look what?");
                return;
            System.out.println(currentRoom.getLongDescription());
         * "Eat" was entered.
         * @param command The command entered.
        private void eat(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Eat what?");
                return;
            System.out.println("You have eaten and are no longer hungry!");
         * "Back" was entered.
         * @param command The command entered.
        private void back(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Back what?");
                return;
            if (previousRoom==null) {
                System.out.println("Can't go back.");
                return;
            // push current room on stack (for stackBack)
            previousRooms.push(currentRoom);
            // swap current and previous rooms (for back)
            Room temp = currentRoom;
            currentRoom = previousRoom;
            previousRoom = temp;
            // You could replace the previous three lines with the following
            // which use the stack to get the previous room
            // but note that this makes "back" dependent on "stackBack".
            // (If you do it this way you no longer need "temp".
            // currentRoom = previousRoom;
            // previousRoom = previousRooms.peek();
            System.out.println("You have gone back:");
            System.out.println(currentRoom.getLongDescription());
         * "StackBack" was entered.
         * @param command The command entered.
        private void stackBack(Command command)
            if(command.hasSecondWord()) {
                System.out.println("StackBack what?");
                return;
            if (previousRooms.isEmpty()) {
                System.out.println("Can't go StackBack.");
                return;
            // set previous room (for "back")
            previousRoom = currentRoom;
            // set new current room (using stack)
            currentRoom = previousRooms.pop();
            System.out.println("You have gone StackBack:");
            System.out.println(currentRoom.getLongDescription());
         * allows a player to take something from the room
         * @param command
        private void take(Command command){
        String a;
        a=command.getSecondWord();
        for (Item i:currentRoom.items()) { //a for each loop, since the room's items are kept in a list, but this gives a                                           //compiler error, it doesn't work because items is an ArrayList, but I need a way to pick up the item. I thought that if //given the item's name, I could run a check through the room's ArrayList of items via a for-each loop
            if (a==i.getName()) {
            removeItem (i);
            return;
         * allows a player to drop an item in the room
         * @param command
        private void drop(Command command) {
            if(command.hasSecondWord()) {
                System.out.println("drop what?");
                return;
            //add item method is suppose to be used here
         * "Quit" was entered. Check the rest of the command to see
         * whether we really quit the game.
         * @param command The command entered.
         * @return true, if this command quits the game, false otherwise.
        private boolean quit(Command command)
            if(command.hasSecondWord()) {
                System.out.println("Quit what?");
                return false;
            else {
                return true;  // signal that we want to quit
    }class Room
    import java.util.*;
    * Class Room - a room in an adventure game.
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * A "Room" represents one location in the scenery of the game.  It is
    * connected to other rooms via exits.  For each existing exit, the room
    * stores a reference to the neighboring room.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.03 October 25, 2007
    public class Room
        private String description;
        private HashMap<String, Room> exits;        // stores exits of this room.
        // The items in the room
        private ArrayList<Item> items;
         * Create a room described "description". Initially, it has
         * no exits. "description" is something like "a kitchen" or
         * "an open court yard".
         * @param description The room's description.
        public Room(String description)
            this.description = description;
            exits = new HashMap<String, Room>();
            items = new ArrayList<Item>();
         * Define an exit from this room.
         * @param direction The direction of the exit.
         * @param neighbor  The room to which the exit leads.
        public void setExit(String direction, Room neighbor)
            exits.put(direction, neighbor);
         * Gives a short description of the room.
         * @return The short description of the room
         * (the one that was defined in the constructor).
        public String getShortDescription()
            return description;
         * Return a description of the items in the room
         * (Note that this could be combined with getLongDescription, but
         * this way shows better cohesion, and could avoid code duplication
         * for future enhancements.)
         * @return A description of the items in this room
        public String getItemsDescription()
            String s = new String();
            if (items.size()==0)
                s += "There are no items in this room.\n";
            else {
                s += "The item(s) in the room are:\n";
                for (Item item : items ) {
                   s += item.getInfo() + "\n";
            return s;
         * Return a description of the room in the form:
         *     You are in the kitchen.
         *     Exits: north west
         *     and information on the items in the room
         * @return A long description of this room
        public String getLongDescription()
            String s = "You are " + description + ".\n" + getExitString() + "\n";
            s += getItemsDescription();
            return s;
         * Return a string describing the room's exits, for example
         * "Exits: north west".
         * @return Details of the room's exits.
        private String getExitString()
            String returnString = "Exits:";
            Set<String> keys = exits.keySet();
            for(String exit : keys) {
                returnString += " " + exit;
            return returnString;
         * Return the room that is reached if we go from this room in direction
         * "direction". If there is no room in that direction, return null.
         * @param direction The exit's direction.
         * @return The room in the given direction.
        public Room getExit(String direction)
            return exits.get(direction);
         * Adds the given item to the room.
         * @param item The item to be added
        public void addItem(Item item)
            items.add(item);
         * Removes an item if the person picks it up
         * @param item the item to be removed
        public void removeItem (Item item)
            items.remove(item);
    }class Item
    * This represents an item in a room in zuul.
    * @author L.S. Marshall
    * @version 1.00 October 9, 2007
    public class Item
        // The description of the item
        private String description;
        // The weight of the item
        private double weight;
        private String name;
         * Constructor for objects of class Item
         * @param desc description of the item
         * @param weight the weight of the item
        public Item(String name, String desc, double weight)
            description = desc;
            this.weight = weight;
            this.name=name;
         * Returns a string representing this item
         * @return string representing this item
        public String getInfo()
            return ("Item: " + description + ", weighs " + weight + ".");
         * returns the name of the string
         * @ return the name in a string
        public String getName()
            return ( name );
    }class Command
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * This class holds information about a command that was issued by the user.
    * A command currently consists of two strings: a command word and a second
    * word (for example, if the command was "take map", then the two strings
    * obviously are "take" and "map").
    * The way this is used is: Commands are already checked for being valid
    * command words. If the user entered an invalid command (a word that is not
    * known) then the command word is <null>.
    * If the command had only one word, then the second word is <null>.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    public class Command
        private String commandWord;
        private String secondWord;
         * Create a command object. First and second word must be supplied, but
         * either one (or both) can be null.
         * @param firstWord The first word of the command. Null if the command
         *                  was not recognised.
         * @param secondWord The second word of the command.
        public Command(String firstWord, String secondWord)
            commandWord = firstWord;
            this.secondWord = secondWord;
         * Return the command word (the first word) of this command. If the
         * command was not understood, the result is null.
         * @return The command word.
        public String getCommandWord()
            return commandWord;
         * @return The second word of this command. Returns null if there was no
         * second word.
        public String getSecondWord()
            return secondWord;
         * @return true if this command was not understood.
        public boolean isUnknown()
            return (commandWord == null);
         * @return true if the command has a second word.
        public boolean hasSecondWord()
            return (secondWord != null);
    }class Parser
    import java.util.Scanner;
    import java.util.StringTokenizer;
    //I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
    //Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
    //yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
    //Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
    //it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * This parser reads user input and tries to interpret it as an "Adventure"
    * command. Every time it is called it reads a line from the terminal and
    * tries to interpret the line as a two word command. It returns the command
    * as an object of class Command.
    * The parser has a set of known command words. It checks user input against
    * the known commands, and if the input is not one of the known commands, it
    * returns a command object that is marked as an unknown command.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.01 October 9, 2007
    public class Parser
        private CommandWords commands;  // holds all valid command words
        private Scanner reader;         // source of command input
         * Create a parser to read from the terminal window.
        public Parser()
            commands = new CommandWords();
            reader = new Scanner(System.in);
         * Command returns the command typed by the user.
         * @return The next command from the user.
        public Command getCommand()
            String inputLine;   // will hold the full input line
            String word1 = null;
            String word2 = null;
            System.out.print("> ");     // print prompt
            inputLine = reader.nextLine();
            // Find up to two words on the line.
            Scanner tokenizer = new Scanner(inputLine);
            if(tokenizer.hasNext()) {
                word1 = tokenizer.next();      // get first word
                if(tokenizer.hasNext()) {
                    word2 = tokenizer.next();      // get second word
                    // note: we just ignore the rest of the input line.
            // Now check whether this word is known. If so, create a command
            // with it. If not, create a "null" command (for unknown command).
            if(commands.isCommand(word1)) {
                return new Command(word1, word2);
            else {
                return new Command(null, word2);
         * Returns a list of valid command words.
         * @string list of valid command words
        public String getCommands()
            return commands.getCommandList();
    }class CommandWords
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game.
    * This class holds an enumeration of all command words known to the game.
    * It is used to recognise commands as they are typed in.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.01 October 9, 2007
    public class CommandWords
        // a constant array that holds all valid command words
        private static final String[] validCommands = {
            "go", "quit", "help", "look", "eat", "back", "stackBack",
            "take", "drop",
         * Constructor - initialise the command words.
        public CommandWords()
            // nothing to do at the moment...
         * Check whether a given String is a valid command word.
         * @param aString the command word
         * @return true if it is, false if it isn't.
        public boolean isCommand(String aString)
            for(int i = 0; i < validCommands.length; i++) {
                if(validCommands.equals(aString))
    return true;
    // if we get here, the string was not found in the commands
    return false;
    * Return a string containing all valid commands.
    * @return string of all valid commands
    public String getCommandList()
    String s="";
    for(String command: validCommands) {
    s += command + " ";
    return s;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    right, sorry, that was thoughtless of me.
    class Parser
    import java.util.Scanner;
    import java.util.StringTokenizer;
    //I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
    //Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
    //yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
    //Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
    //it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
    * This class is part of the "World of Zuul" application.
    * "World of Zuul" is a very simple, text based adventure game. 
    * This parser reads user input and tries to interpret it as an "Adventure"
    * command. Every time it is called it reads a line from the terminal and
    * tries to interpret the line as a two word command. It returns the command
    * as an object of class Command.
    * The parser has a set of known command words. It checks user input against
    * the known commands, and if the input is not one of the known commands, it
    * returns a command object that is marked as an unknown command.
    * @author  Michael Kolling and David J. Barnes
    * @version 2006.03.30
    * @author L.S. Marshall
    * @version 1.01 October 9, 2007
    public class Parser
        private CommandWords commands;  // holds all valid command words
        private Scanner reader;         // source of command input
         * Create a parser to read from the terminal window.
        public Parser()
            commands = new CommandWords();
            reader = new Scanner(System.in);
         * Command returns the command typed by the user.
         * @return The next command from the user.
        public Command getCommand()
            String inputLine;   // will hold the full input line
            String word1 = null;
            String word2 = null;
            System.out.print("> ");     // print prompt
            inputLine = reader.nextLine();
            // Find up to two words on the line.
            Scanner tokenizer = new Scanner(inputLine);
            if(tokenizer.hasNext()) {
                word1 = tokenizer.next();      // get first word
                if(tokenizer.hasNext()) {
                    word2 = tokenizer.next();      // get second word
                    // note: we just ignore the rest of the input line.
            // Now check whether this word is known. If so, create a command
            // with it. If not, create a "null" command (for unknown command).
            if(commands.isCommand(word1)) {
                return new Command(word1, word2);
            else {
                return new Command(null, word2);
         * Returns a list of valid command words.
         * @string list of valid command words
        public String getCommands()
            return commands.getCommandList();
    }

  • 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);
    }

  • Help needed with passing data between classes, graph building application?

    Good afternoon please could you help me with a problem with my application, my head is starting to hurt?
    I have run into some difficulties when trying to build an application that generates a linegraph?
    Firstly i have a gui that the client will enter the data into a text area call jta; this data is tokenised and placed into a format the application can use, and past to a seperate class that draws the graph?
    I think the problem lies with the way i am trying to put the data into co-ordinate form (x,y) as no line is being generated.
    The following code is from the GUI:
    +public void actionPerformed(ActionEvent e) {+
    +// Takes data and provides program with CoOrdinates+
    int[][]data = createData();
    +// Set the data data to graph for display+
    grph.showGrph(data);
    +// Show the frame+
    grphFrame.setVisible(true);
    +}+
    +/** set the data given to the application */+
    +private int[][] createData() {+
    +     //return data;+
    +     String rawData = jta.getText();+
    +     StringTokenizer tokens = new StringTokenizer(rawData);+
    +     List list = new LinkedList();+
    +     while (tokens.hasMoreElements()){+
    +          String number = "";+
    +          String token = tokens.nextToken();+
    +          for (int i=0; i<token.length(); i++){+
    +               if (Character.isDigit(token.charAt(i))){+
    +                    number += token.substring(i, i+1);+
    +               }+
    +          }     +
    +     }+
    +     int [][]data = new int[list.size()/2][2];+
    +     int index = -2;+
    +     for (int i=0; i<data.length;i++){+
    +               index += 2;+
    +               data[0] = Integer.parseInt(+
    +                         (list.get(index).toString()));+
    +               data[i][1] = Integer.parseInt(+
    +                         (list.get(index +1).toString()));+
    +          }+
    +     return data;+
    The follwing is the coding for drawing the graph?
    +public void showGrph(int[][] data)  {+
    this.data = data;
    repaint();
    +}     +
    +/** Paint the graph */+
    +protected void paintComponent(Graphics g) {+
    +//if (data == null)+
    +     //return; // No display if data is null+
    super.paintComponent(g);
    +// x is the start position for the first point+
    int x = 30;
    int y = 30;
    for (int i = 0; i < data.length; i+) {+
    +g.drawLine(data[i][0],data[i][1],data[i+1][0],data[i+1][1]);+
    +}+
    +}+

    Thanks for that tip!
    package LineGraph;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.List;
    public class GUI extends JFrame
      implements ActionListener {
      private JTextArea Filejta;
      private JTextArea jta;
      private JButton jbtShowGrph = new JButton("Show Chromatogram");
      public JButton jbtExit = new JButton("Exit");
      public JButton jbtGetFile = new JButton("Search File");
      private Grph grph = new Grph();
      private JFrame grphFrame = new JFrame();   // Create a new frame to hold the Graph panel
      public GUI() {
         JScrollPane pane = new JScrollPane(Filejta = new JTextArea("Default file location: - "));
         pane.setPreferredSize(new Dimension(350, 20));
         Filejta.setWrapStyleWord(true);
         Filejta.setLineWrap(true);     
        // Store text area in a scroll pane 
        JScrollPane scrollPane = new JScrollPane(jta = new JTextArea("\n\n Type in file location and name and press 'Search File' button: - "
                  + "\n\n\n Data contained in the file will be diplayed in this Scrollpane "));
        scrollPane.setPreferredSize(new Dimension(425, 300));
        jta.setWrapStyleWord(true);
        jta.setLineWrap(true);
        // Place scroll pane and button in the frame
        JPanel jpButtons = new JPanel();
        jpButtons.setLayout(new FlowLayout());
        jpButtons.add(jbtShowGrph);
        jpButtons.add(jbtExit);
        JPanel searchFile = new JPanel();
        searchFile.setLayout(new FlowLayout());
        searchFile.add(pane);
        searchFile.add(jbtGetFile);
        add (searchFile, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(jpButtons, BorderLayout.SOUTH);
        // Exit Program
        jbtExit.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
             System.exit(0);
        // Read Files data contents
         jbtGetFile.addActionListener(new ActionListener(){
         public void actionPerformed( ActionEvent e) {
                   String FileLoc = Filejta.getText();
                   LocateFile clientsFile;
                   clientsFile = new LocateFile(FileLoc);
                        if (FileLoc != null){
                             String filePath = clientsFile.getFilePath();
                             String filename = clientsFile.getFilename();
                             String DocumentType = clientsFile.getDocumentType();
         public String getFilecontents(){
              String fileString = "\t\tThe file contains the following data:";
         return fileString;
           // Register listener     // Create a new frame to hold the Graph panel
        jbtShowGrph.addActionListener(this);
        grphFrame.add(grph);
        grphFrame.pack();
        grphFrame.setTitle("Chromatogram showing data contained in file \\filename");
      /** Handle the button action */
      public void actionPerformed(ActionEvent e) {
        // Takes data and provides program with CoOrdinates
        int[][]data = createData();
        // Set the data data to graph for display
        grph.showGrph(data);
        // Show the frame
        grphFrame.setVisible(true);
      /** set the data given to the application */
      private int[][] createData() {
           String rawData = jta.getText();
           StringTokenizer tokens = new StringTokenizer(rawData);
           List list = new LinkedList();
           while (tokens.hasMoreElements()){
                String number = "";
                String token = tokens.nextToken();
                for (int i=0; i<token.length(); i++){
                     if (Character.isDigit(token.charAt(i))){
                          number += token.substring(i, i+1);
           int [][]data = new int[list.size()/2][2];
           int index = -2;
           for (int i=0; i<data.length;i++){
                     index += 2;
                     data[0] = Integer.parseInt(
                             (list.get(index).toString()));
                   data[i][1] = Integer.parseInt(
                             (list.get(index +1).toString()));
         return data;
    public static void main(String[] args) {
    GUI frame = new GUI();
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Clients Data Retrival GUI");
    frame.pack();
    frame.setVisible(true);
    package LineGraph;
    import javax.swing.*;
    import java.awt.*;
    public class Grph extends JPanel {
         private int[][] data;
    /** Set the data and display Graph */
    public void showGrph(int[][] data) {
    this.data = data;
    repaint();
    /** Paint the graph */
    protected void paintComponent(Graphics g) {
    //if (data == null)
         //return; // No display if data is null
    super.paintComponent(g);
    //Find the panel size and bar width and interval dynamically
    int width = getWidth();
    int height = getHeight();
    //int intervalw = (width - 40) / data.length;
    //int intervalh = (height - 20) / data.length;
    //int individualWidth = (int)(((width - 40) / 24) * 0.60);
    ////int individualHeight = (int)(((height - 40) / 24) * 0.60);
    // Find the maximum data. The maximum data
    //int maxdata = 0;
    //for (int i = 0; i < data.length; i++) {
    //if (maxdata < data[i][0])
    //maxdata = data[i][1];
    // x is the start position for the first point
    int x = 30;
    int y = 30;
    //draw a vertical axis
    g.drawLine(20, height - 45, 20, (height)* -1);
    // Draw a horizontal base line4
    g.drawLine(20, height - 45, width - 20, height - 45);
    for (int i = 0; i < data.length; i++) {
    //int Value = i;      
    // Display a line
    //g.drawLine(x, height - 45 - Value, individualWidth, height - 45);
    g.drawLine(data[i][0],data[i][1],data[i+1][0],data[i+1][1]);
    // Display a number under the x axis
    g.drawString((int)(0 + i) + "", (x), height - 30);
    // Display a number beside the y axis
    g.drawString((int)(0 + i) + "", width - 1277, (y) + 900);
    // Move x for displaying the next character
    //x += (intervalw);
    //y -= (intervalh);
    /** Override getPreferredSize */
    public Dimension getPreferredSize() {
    return new Dimension(1200, 900);

Maybe you are looking for

  • Comparing currency of an Opportunity with product revenue line

    Hello, I am trying to build a report that will display all the opportunities and the product revenue records where the currency on opportunity records do not match the corresponding currency on the related pportunity product revenue records. Any sugg

  • Generate Report From Template (Excel).vi & don't understand to fill the cells

    I am trying to use the Generate Report From Template (Excel).vi to build my own template, and then fill it with some of my datas. I am trying to replace the "temperature" or "pressure" labels by others, and then fill them with my vi. I don't understa

  • SSRS Parameters help!

    Dear All, sorry my last post was not written properly. I need some urgent help creating a report on SSRS (Microsoft Visual Studio 2008) I am currently using certain parameters to get a specific data list. Only after this list has been created I want

  • Excise Duties are not appearing in GR

    Hi Experts, User has created a Scheduling agreement and maintained Excise conditions in Agreement. When he tried to do Goods receipt,he is not able to see Excise tab in Goods receipt.What would be the reason for this? Please anyone can tell me.... Th

  • Privacy browser option is missing

    I am trying to set up my yahoo mail and it is telling me to turn off privacy browser by going setting, safari privacy browser.  There is no privacy browser option?