-
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
-
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 01: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
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks