Solved

Reading tokens into an array ?

Posted on 1998-08-17
13
388 Views
Last Modified: 2010-03-30
Hi !

I am trying to read data from a file into an array. This array of data is later used for drawing purposes( actually presenting extra information beneath a horizontal line. )

My question is: how to convert the already read tokens and set them into an opened array, so that the drawing will be possible later. The length of the data items is unknown, possibly dates or what so ever.

The code looks like this:

       import java.applet.Applet;
       import java.awt.Graphics;
       import java.net.URL;
       import java.io.*;
       import java.util.*;

       // The aim is to draw text/numbers from the "Iitem" file
       //  beneath the "comb's" horizontal line

  public class Teksti extends Applet {

         String iName;
         Graphics graphics;
         int boxXborder, boxYborder, xSkaala, ySkaala, size;
         int tokenItype;

         String[] Iitem;
         StreamTokenizer stI;

         public void paint(Graphics g) {
           graphics = g;

           boxXborder = 400;
           boxYborder = 400;
           xSkaala = 1;
           ySkaala = 1;

           g.drawRect(0,0,boxXborder,boxYborder);
           // Box of the given size

           int div;
           div = boxXborder/size;
           int up;
           int down;
           up = boxYborder - 15;
           down = boxYborder - 5;

           for (int t=0; t<(div-1); t++) {
           g.drawLine(t*div, up, t*div, down);
               }

           // Vertical lines

           g.drawLine(0,(boxYborder - 10), boxXborder, (boxYborder - 10));
           // Horizontal line of the 'comb'


           for (int t=0;t<(div-1); t++) {
           g.drawString(Iitem[t], t*div, (boxYborder - 8));
                }
           // Data items beneath the horizontal line

           }


  public void init() {

           try {
             iName = getParameter("Iitems");
             size = Integer.parseInt(getParameter("Size"));
           }
           catch (Exception e) {
             System.err.println("No file found."+e);
             System.err.println(e.toString());
           }


           String Iitem[] = new String [size];
          // Here I open a matrix for the items of given size

           readDataFiles();
           // init now calls readDataFiles();
    }

         /* In this part I should get the name of the item file needed.
          * The amount of file items is given as 'size'.    */



         public synchronized void readDataFiles() {


           // Here I want to read

           try {

           // This creates the StreamTokenizer in a non-deprecated manner


             stI = new StreamTokenizer(new InputStreamReader(new URL(getDocumentBase(),
                   iName).openConnection().getInputStream()));

             tokenItype = stI.nextToken();

         } catch (IOException e) {System.out.println(e.toString());}


          int i;
          i = -1;
          while (stI.ttype != StreamTokenizer.TT_EOF)
         {
           i++;
           if (stI.ttype == StreamTokenizer.TT_WORD)
             {
               try {

                Iitem[i] = stI.nextToken.toString();

         // Here I am trying to read tokens and set them as table items

               } catch (IOException e) { System.err.println(e.toString()); }
             }
             else
               System.out.println("Invalid token " + stI.sval);
         }


         // This file read is one consisting of interesting data items


         
         
    }


}


Best thanks for your help !
0
Comment
Question by:kojonen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
13 Comments
 
LVL 1

Expert Comment

by:datadesign
ID: 1220071
k, how i understand u, u want just wnat to put some things
into an array, but u r not knowing how big these things r....

So, what u need is to use a Vector !
u can put as many Objects into a Vector as u want.
I think this should solve your problem...
(for more information about Vector,take a look at the class)

hope this helps u :)
0
 

Author Comment

by:kojonen
ID: 1220072
Yeah ! It's all about reading. But the main problem is how to convert tokens into strings.
That means that I'd like to have strings in an array.

For example: How to do this convesion if my data file would consist of the following dates
1.1  2.1  3.1  4.1  5.1  6.1  7.jan

So you see I I don't what the data will be. That depens of the file I am reading.
However I'd like to have a program code which is acceptable for all data types.

I think I should do the convesion from tokens to strings. Maybe this isn't the right way. Any way I'm trustful waiting for good tips. Thanks !
0
 
LVL 2

Expert Comment

by:bernfarr
ID: 1220073
The StreamTokenizer will give you values are strings or as numbers, depending on what it detects. So the question is, do you want to store all the array values are strings, or do you want the array to hold different types, depending on the input type of the token as determined by StreamTokenizer.

You probably already know this type of code.
if (stl.ttype == StreamTokenizer.TT_NUMBER )
  // It's a number
else if ( stl.ttype == StreamTokenizer.TT_WORD )
  // it's a string

0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
LVL 16

Expert Comment

by:imladris
ID: 1220074
If I understand correctly, you have a data stream, some elements of which might appears as numbers to the stream tokenizer, some might appear as strings.

I think the answer, in that case is to do the last loop as follows:


          while (stI.nextToken() != StreamTokenizer.TT_EOF)
         {               // get next token until EOF
           i++;
           if (stI.ttype == StreamTokenizer.TT_WORD)
             {
                litem[i]=stl.sval;
                // if current token is a string, assign it to litem
             }
           else if(stl.ttype==StreamTokenizer.TT_NUMBER)
            {   litem[i]=Double.toString(stl.nval);
                // convert number to string
            }
             else
               System.out.println("Invalid token " + stI.sval);
         }

0
 
LVL 16

Expert Comment

by:imladris
ID: 1220075
So, that way, each of the items is converted to a string, and you can easily display them under the line.

0
 

Author Comment

by:kojonen
ID: 1220076
Best thanks for all !

I tried and liked the imlandris' solution a lot. However, it still need a sligth refinement because of IOExceptions. I still like to know how exactly should I write these IOException throws to get this code working.

The code is above,

       import java.applet.Applet;
       import java.awt.Graphics;
       import java.net.URL;
       import java.io.*;
       import java.util.*;

       // The aim is to draw text/numbers from the "Iitem" file
       //  beneath the "comb's" horizontal line

  public class Teksti extends Applet {

         String iName;
         Graphics graphics;
         int boxXborder, boxYborder, xSkaala, ySkaala, size;
         int tokenItype;

         String[] Iitem;
         StreamTokenizer stI;

         public void paint(Graphics g) {
           graphics = g;

           boxXborder = 400;
           boxYborder = 400;
           xSkaala = 1;
           ySkaala = 1;

           g.drawRect(0,0,boxXborder,boxYborder);
           // Box of the given size

           int div;
           div = boxXborder/size;
           int up;
           int down;
           up = boxYborder - 15;
           down = boxYborder - 5;

           for (int t=0; t<(div-1); t++) {
           g.drawLine(t*div, up, t*div, down);
               }

           // Vertical lines

           g.drawLine(0,(boxYborder - 10), boxXborder, (boxYborder - 10));
           // Horizontal line of the 'comb'


           for (int t=0;t<(div-1); t++) {
           g.drawString(Iitem[t], t*div, (boxYborder - 8));
                }
           // Data items beneath the horizontal line

           }


  public void init() {

           try {
             iName = getParameter("Iitems");
             size = Integer.parseInt(getParameter("Size"));
           }
           catch (Exception e) {
             System.err.println("No file found."+e);
             System.err.println(e.toString());
           }


           String Iitem[] = new String [size];
          // Here I open a matrix for the items of given size

           readDataFiles();
           // init now calls readDataFiles();
    }

         /* In this part I should get the name of the item file needed.
          * The amount of file items is given as 'size'.    */



         public synchronized void readDataFiles() {


           // Here I want to read

           try {

           // This creates the StreamTokenizer in a non-deprecated manner


             stI = new StreamTokenizer(new InputStreamReader(
             new URL(getDocumentBase(),  iName).openConnection().getInputStream()));

             tokenItype = stI.nextToken();

         } catch (IOException e) {System.out.println(e.toString());}



    int i;
    i = -1;

    while (stI.nextToken() != StreamTokenizer.TT_EOF)
             {       // get next token until EOF
               i++;
               if (stI.ttype == StreamTokenizer.TT_WORD)
                 {
                    Iitem[i]= stI.sval;
                   
                    // if current token is a string, assign it to litem
                 }
               else if(stI.ttype==StreamTokenizer.TT_NUMBER)
                {   Iitem[i]=Double.toString(stI.nval);
                    // convert number to string
                }
                 else
                   System.out.println("Invalid token " + stI.sval);
             }





         // This file read is one consisting of interesting data items




    }


}
0
 
LVL 16

Expert Comment

by:imladris
ID: 1220077
Upon inspection I assume that the IOException problem you're having is on this line:

  while (stI.nextToken() != StreamTokenizer.TT_EOF)

It is due to the fact that nextToken can throw an IOException.
The solution, as always, can be one of two, either declare the
routine to throw exception, or handle it with a try/catch block. The latter seems more appropriate here, since that is what is done with the other IOExceptions in readDataFiles. So the last loop should be something like:

try
{   while (stI.nextToken() != StreamTokenizer.TT_EOF)
             {       // get next token until EOF
               i++;
               if (stI.ttype == StreamTokenizer.TT_WORD)
                 {
                    Iitem[i]= stI.sval;
                    
                    // if current token is a string, assign it to litem
                 }
               else if(stI.ttype==StreamTokenizer.TT_NUMBER)
                {   Iitem[i]=Double.toString(stI.nval);
                    // convert number to string
                }
                 else
                   System.out.println("Invalid token " + stI.sval);
             }
} catch(IOException e){System.out.println(e.toString());

or alternatively you could enclose all the code in readDataFiles in a single try/catch block.

0
 

Author Comment

by:kojonen
ID: 1220078
Best thanks imlandris !

Your piece of advice did help to get rid of "IOException"-problem. Thanks !  And I'm really thankful for your help so far, it's really been important for me. Unfortunately the code isn't working yet and I got to keep the question open.

Now I have a problem with "NullPointerException". How come ?

The slightly modified code is here:

       import java.applet.Applet;
       import java.awt.Graphics;
       import java.net.URL;
       import java.io.*;
       import java.util.*;

       // The aim is to draw text/numbers from the "Iitem" file
       //  beneath the "comb's" horizontal line

  public class Teksti extends Applet {

         String iName;
         Graphics graphics;
         int boxXborder, boxYborder, xSkaala, ySkaala, size;
         int tokenItype;

         String[] Iitem;
         StreamTokenizer stI;

         public void paint(Graphics g) {
           graphics = g;

           boxXborder = 400;
           boxYborder = 400;
           xSkaala = 1;
           ySkaala = 1;

           g.drawRect(0,0,boxXborder,boxYborder);
           // Box of the given size

           int div;
           div = boxXborder/size;
           int up;
           int down;
           up = boxYborder - 15;
           down = boxYborder - 5;

           for (int t=0; t<(div-1); t++) {
           g.drawLine(t*div, up, t*div, down);
               }

           // Vertical lines

           g.drawLine(0,(boxYborder - 10), boxXborder, (boxYborder - 10));
           // Horizontal line of the 'comb'


           for (int t=0;t<(div-1); t++) {
           g.drawString(Iitem[t], t*div, (boxYborder - 8));
                }
           // Data items beneath the horizontal line

           }


  public void init() {

           try {
             iName = getParameter("Iitems");
             size = Integer.parseInt(getParameter("Size"));
           }
           catch (Exception e) {
             System.err.println("No file found."+e);
             System.err.println(e.toString());
           }


           String Iitem[] = new String [size];
          // Here I open a matrix for the items of given size
                                                       
          try
            {
             readDataFiles();
           }
            catch (Exception e)
              {
               System.err.println("Problems while reading file: "+e);
               e.printStackTrace();
               }

   }

         /* In this part I should get the name of the item file needed.
          * The amount of file items is given as 'size'.    */



    public synchronized void readDataFiles() {

           try {

           // This creates the StreamTokenizer in a non-deprecated manner


             stI = new StreamTokenizer(new InputStreamReader(new                                   URL(getDocumentBase(), iName).openConnection().getInputStream()));

                tokenItype = stI.nextToken();
             
               } catch (IOException e) {System.out.println(e.toString());}

         
          int i;
          i = -1;
          try{
              while (stI.nextToken() != StreamTokenizer.TT_EOF)
                 {       // get next token until EOF
                   i++;
                   if (stI.ttype == StreamTokenizer.TT_WORD)
                     {
                        Iitem[i]= stI.sval;

                        // if current token is a string, assign it to litem
                     }
                   else if(stI.ttype==StreamTokenizer.TT_NUMBER)
                    {   Iitem[i]=Double.toString(stI.nval);
                        // convert number to string
                    }
                     else
                       System.out.println("Invalid token " + stI.sval);
                  }
             } catch(IOException e){System.out.println(e.toString()); }

   
        // In this part the interesting data items are read from the file

    }

    }
   


And my html-page looks like this:

<HTML>
<HEAD>
<TITLE>Teksti</TITLE>
</HEAD>
<BODY>
<H1>Teksti</H1>
<HR>
<APPLET code="Teksti.class"  WIDTH=401 HEIGHT=401>
<PARAM name="Iitems" value="Inumerot.txt">
<PARAM name="Size" value=7>
</APPLET>      
<HR>
</BODY>
</HTML>

And my data file "Inumerot.txt" like this:

1.1
2.1
3.1
4.1
5.1
6.1
7.jan





0
 
LVL 3

Expert Comment

by:mjenkins
ID: 1220079
kojonen,

Etiquette would dictate that since imlandris has moved you substantially in the right direction toward an answer, you should leave the "lock" on the question and give him/her the opportunity to complete the answer to your satisfaction. I bring this to your attention for your benefit. If you gain a reputation for unreasonably rejecting expert's answers, you may find fewer of the experts willing to look at your questions.

I realize that this is probably completely unintentional on your part (the "answer" forms can be less than clear), but wanted to share with you so that you always have the best opportunity to recieve the highest quality answers.

0
 
LVL 16

Accepted Solution

by:
imladris earned 60 total points
ID: 1220080
It would be tremendously helpful if you could indicate what line an error occurred on. We have also gone a long ways past the original question. There comes a point where it is fairer to close one question, and start a new one.

The NullPointerException is caused by the fact that this line in init:

          String Iitem[] = new String [size];

creates and initializes a local variable. But this line in readDataFiles:

                    {   Iitem[i]=Double.toString(stI.nval);
  
refers to the instance variable that was declared at the beginning of the class. The solution is to drop the declaration on the init line. It should be:

Iitem=new String[size];

In this way, the instance variable will be initialized and readDataFiles will be able to use it.

0
 

Author Comment

by:kojonen
ID: 1220081
Best thanks Imladris !

This helped me to get rid of the NullPointerException. Now I'm working with another one, namely with ArrayOutOfIndex...

In case I don't manage with it, I'll open a new question as You suggested.

Anyway, now the code is reading data into one dimensional matrix, and the original question is fairly solved.

TK
0
 

Author Comment

by:kojonen
ID: 1220082
mjenkins

Best thanks for Your piece of advice.

As You said it's really been unintentional from my side not to give points straight to Mr. imladris. This is due to the fact that I didn't know what would have happened then. Namely, I thought the question and its problems might stay there because the solution searching would stop.

Well, as a newcomer to this site I'm working on to learn the manners correctly. And java
as well.

TK


0
 
LVL 16

Expert Comment

by:imladris
ID: 1220083
Just to be sure you don't go to the other extreme:

the theory is that you keep adding comments (without rejecting the answer) containing questions or clarifications (i.e. you have a "conversation" with the expert) until either the question is answered to your satisfaction, or you don't think you're making progress. In the first case you grade the question, in the second you reject the answer/reopen the question.


Thanks, by the way. It was a pleasure helping you.


0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
runtime exception 2 66
pagenation logic how it is working in my code 1 81
jsp insert to database example 2 89
dao vs facade design patterns 2 69
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question