Computer Science Example
Reading from a file into an array of objects

import java.io.*;
import java.text.*;

public class Orders
{
     public static void main (String [] args)
     {
          OrderList orderList = new OrderList ();
          orderList.readOrders ();
          orderList.displayOrders ();
          orderList.totalCost ();
     } // constructor
} // class Orders

class OrderList
{
     private Order [] list;
     final int maxSize = 10;
     private int listSize;
 
     OrderList ()
     {
          list = new Order [maxSize];
          listSize = 0;
     } // constructor
 
     public void readOrders ()
     {
          String title;
          try
          {
               BufferedReader orderFile = new BufferedReader (new InputStreamReader (new FileInputStream ("orderFile.txt")));
               title = orderFile.readLine ();
               while ((title != null) && (listSize < maxSize))
               {
                    Order order = new Order (title);
                    order.readOrder (orderFile);
                    list [listSize] = order;
                    listSize ++;
                    title = orderFile.readLine ();
               }
               orderFile.close ();
          }catch (IOException e) {System.out.println ("File Error");}
     } // method readOrders
 
     public void displayOrders ()
     {
          for (int count = 0; count < listSize; count ++)
               list [count].displayOrder ();
      } // method displayOrders
 
     public void totalCost ()
     {
          double total = 0;
          for (int count = 0; count < listSize; count ++)
          {
               double price = list[count].getPrice ();
               int quantity = list[count].getQuantity ();
               total += price * quantity;
          }
          System.out.println ("The total cost is " + NumberFormat.getCurrencyInstance ().format (total));
     } // method totalCost
 } // class OrderList

class Order
{
     private String productName, id;
     private double price;
     private int quantity;
 
     Order (String name)
     {
          productName = name;
     } // constructor
 
     public double getPrice () {return price;}
     public int getQuantity () { return quantity;}
 
     public void readOrder (BufferedReader orderFile) throws IOException
     {
          id = orderFile.readLine ();
          price = Double.parseDouble (orderFile.readLine ());
          quantity = Integer.parseInt (orderFile.readLine ());
     } // method readOrder
 
     public void displayOrder ()
     {
          System.out.println ("Product Name: " + productName);
          System.out.println ("Product ID: " + id);
          System.out.println ("Price: " + price);
          System.out.println ("Quantity: " + quantity);
     } // method displayOrder
} // class Order