how to read text file that contains price and the item into an array


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: how to read text file that contains price and the item into an array

  1. #1
    Join Date
    Sep 2006
    Posts
    1

    how to read text file that contains price and the item into an array

    I am having difficulty in reading the inventory.txt file.
    The text file looks like this:

    21.95 Water Filter Pack
    .51 Pork and Beans
    1.79 Chicken Salad Sandwich
    5.99 Coke 24-pack

    Here is my code:

    public ListOfItems(String filename){
    this.filename=filename;
    storeItems=new StoreItem[4];

    if(filename==null)
    storeItems=new StoreItem[0];

    try{
    FileReader fr=new FileReader(filename);
    BufferedReader br=new BufferedReader(fr);

    String line;
    int index=0;

    while((line=br.readLine())!=null){


    StringTokenizer tokenizer=new StringTokenizer(line);

    Double price=Double.parseDouble(tokenizer.nextToken());

    String item=tokenizer.nextToken();

    while(tokenizer.hasMoreTokens()){

    item=tokenizer.nextToken();

    storeItems[index++]=newStoreItem(price, item);


    }
    }

    System.out.println(storeItems);

    br.close();
    }

    When I run the program I get an error message that says unable to read due to my catch statement that I used after the try block. I also get an error that says array index out of bounds exception: 4

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    What is your catch statement?

    Have you thought about using the Scanner class for this?

    Do your first cut with the delimiter being new line.

    Take each element of the resulting array, create a new scanner instance using space as the delimiter, then with that resulting array, use nextFloat() to get the price, then build a StringBuilder object using next() while hasNext() to get the item.
    Last edited by nspils; 09-17-2006 at 02:28 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center