Connect flat file data to your live objects in Java OOP

Data Processing using OOP in Java

Connecting database files to live objects in Java

ACSE 2012 Session Description

Transitioning from Procedural to Object-Oriented Programming through Parsing and Data Processing

In this session we will look at traditional procedural programming tasks and translate them into object-oriented programs. We will transition from procedural programmers (“in the main”) to object-oriented programmers by designing Java programs with multiple classes. We will learn how to read and parse flat file databases (.txt files) and link data to live objects in Java programs.

In addition, we will explore parsing strategies, arraylists, object-oriented design (constructors, implementing the instantiation of an object (keyword: new), setters, getters, libraries, abstraction, inheritance (IS-A), composition (HAS-A)), UML and MVC as part of our workflow.

Participants will have access to an online tutorial to practice the skills introduced in the session.

Stage 1 - Programming in the MAIN

When I first programmed in Java back in 2002 I was a “procedural” Java programmer where all code was located in the main. It is a good way to start programming in Java after you have completed the HelloWorld project because it allows people new to Java to get their feet wet with the new syntax, IDE, documentation and types of errors. I often start with the AgeInSeconds lab to get people started in Java or any other language for that matter. Listed below is a very simple AgeInSeconds lab:

public class AgeInSeconds {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int age = 16;
		System.out.println("age is " + age);
		int days = age * 365;
		System.out.println("age in days " + days);
		int hours = days * 24;
		System.out.println("age in hours " + hours);
		int minutes = hours * 60;
		System.out.println("age in minutes " + minutes);
		int seconds = minutes * 60;
		System.out.println("age in seconds " + seconds);
	} // end main

}// end class

This lab works well because it forces students to think “algorithmically” and to be persistent when coding. After we start programming objects in Java (ex. Circle – UseCircle) then we can come back to this lab and jazz it up using object-oriented design.

Group Q : How could we change the AgeInSeconds lab to be object-oriented? What are the real world objects involved in this task? Let’s be ABSTRACT!

Answer : We are talking about a “person”. We need to use “abstraction” to be good OO programmers. Why not create a Person class and perhaps we can get the program to prompt the user for his name and age? What do we need to add to the Person class to make it mutable or capable of change? Yes, we need “setters”. Now, we can introduce Scanner (external libraries : golf club analogy), getters VS setters, methods (void versus return) , toString, different data types and we are off to the races with OO programming.

Task 1 : Re-write the AgeInSeconds lab to use two classes: Person (the model), AgeInSeconds (the driver: controller). Let’s create a UML diagram of Person class. What is MVC? What is the M, V and C of this programming task?

UML : Universal Modelling Language

- name : String - age: int
+ Person() : constructor + void setName + void setAge + getName + getAge

Solution: Work with group to develop a solution. Note: Sometimes it is easier to build on previous labs after trying some different type problems to facilitate learning. For example, I might “reuse” the Person class to create a Student class which would introduce inheritance or the IS-A relationship (a student is-a person):

public class Student extends Person(){

super(name, age);

.. add student-specific code


What if we want to add students to a class? We could use our Person class along with Student class to demonstrate composition or the HAS-A relationship (a Class has-a Student). More on this later.



Let’s take a moment a look at what the Person class look like in code:

import java.util.Scanner;

public class Person {
	private String name;
	private int age;

	public Person(){
		// empty constructor
	public Person(String name, int age){ = name;
		this.age = age;
	 * @return Returns the name.
	public String getName() {
		return name;
	 * @param sets the name.
	public void setName() {
		System.out.println("What's your name?");
		Scanner input = new Scanner (; =;
	 * @return Returns the lastName.
public void setAge() {
		System.out.println("What's your age?");
		Scanner input = new Scanner (;
		this.age = input.nextInt();

 * @return Returns the name.
public int getAge() {
	return age;

	public String toString(){
		return "## Name : "", Age : "+ this.age;

Students and adults like to interact with their programs when they are learning and that explains why we import the Scanner class to get input from the keyboard. The toString() method is part of the Object class and provides us feedback on the integrity of our user-defined object.

Next, we need to design a driver class that will test our object and see if it generates the same results of our “procedural” AgeInSeconds class:

public class OOPAgeInSeconds {

	 * @param args
	public OOPAgeInSeconds(){
	 // empty constructor	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person p = new Person();
        // implement or instantiate Person object = "bring it to life" : tightly
        // coupled
		int age = p.getAge();
		System.out.println("age is " + age);
		int days = age * 365;
		System.out.println("age in days " + days);
		int hours = days * 24;
		System.out.println("age in hours " + hours);
		int minutes = hours * 60;
		System.out.println("age in minutes " + minutes);
		int seconds = minutes * 60;
		System.out.println("age in seconds " + seconds);

	}// end of main

}// end of class

The OOPAgeInSeconds driver class works and generates the desired output. The code listed above demonstrates two types of constructors, getters, setters, this and the toString() method. Now, we have a model ( that we can reuse in other projects. This part of the tutorial demonstrates how we use “abstraction” to create a model or the Person class and how constructors makes visible or public the data that is hidden or encapsulated by the model (ex. name and age). The “this” operator makes the user input live and assigns user input from the keyboard to the user-defined instance variables built into the object or model.

Task 1

Let’s test your understanding of object-oriented design by repairing a a broken program that I found on the Internet. Something critical to the program is missing. All object-oriented programs must be driven or run from the main. Therefore, you must run the class that has the main inside when working with the Eclipse IDE. Here is the partial program that you will need to reverse engineer to get working:

public class Weekend {

        public static void main(String [] args) {

        // Set up a series of film objects

        Film Watch[] = new Film[4]; // Watch is an array of film objects
        Watch[0] = new Film("Shrek",133);
        Watch[1] = new Film("Road to Perdition",117);
        Watch[2] = new Film("The Truth about Cats and Dogs",93);
        Watch[3] = new Film("Enigma",114);

        Film Longest = null, Shortest = null; // To avoid a grumpy compiler
        int longtime = 0, shorttime = 0; // To avoid a grumpy compiler

        for (int i=0; i < Watch.length; i++) {
                int mins = Watch[i].getminutes(0);  // must provide initial value zero 
                if (i == 0) {
                        Shortest = Longest = Watch[i];
                        shorttime = longtime = mins;
                } else {
                        if (mins < shorttime) {
                                Shortest = Watch[i];
                        if (mins > longtime) {
                                Longest = Watch[i];
        System.out.println("Longest film is " +
                        Longest.getcalled("") +     // must provide initial value "" for string
                        " at "+longtime+" minutes");
        System.out.println("Shortest film is " +
                        Shortest.getcalled("") +
                        " at "+shorttime+" minutes");


The above code needs another class to work. You could start the project by setting it up as “The Movie Project” in Eclipse. Add the Weekend class to the project by right clicking on “The Movie Project” in Eclipse. Name the class “Weekend” and click on the checkbox for main. Next, you must decide what additional class needs to be added to the project to make it work. Good luck. Prize to the first person to solve this OO reverse engineering task!!

Review solution to the Broken Program.

Object-oriented design (OOD) can be difficult to get your head around and sometimes it’s important to step back in the “main” for your sanity. I like to introduce the Marks Program at this point to cover some important concepts; arrays, Swing library for GUI input, parsing GUI, finding MAX value and so on. To start this sequence of labs we create a project in Eclipse called “The Marks Program”. Add a class to the project called “”. Here is the source code for the first lab in the sequence:

public class Marks {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// declares an array of integers
        int[] grades;

        // allocates memory for 10 integers
        grades = new int[4];
        // initialize first element
        grades[0] = 60;
        // initialize second element
        grades[1] = 70;
        // etc.
        grades[2] = 46;
        grades[3] = 90;
        double total = 0;
        // accumulator must be set to zero at the start
        for (int g=0;g < 4;g++){
        	total = total + grades[g];
        }// end for
		double average = total/4;
		System.out.println("The average is " + average);

	}// end main
}//end class

In the program listing above you can see a straight forward review of concepts. You can use this lab to cover array index, elements and bound, accumulators (ex. total). In addition, you can demonstrate how a “for” loop works best with arrays. In the final sequence of the marks program, I ask students to add “” to “The Marks Program” folder in Eclipse. You can see how we have introduced more concepts and added some “entertainment” value to programming in Java in the lab below:

import javax.swing.*;

// find top grade or MAX value in the array = use Javabits Math website
// find MIN value
// use Bubblesort to sort array in ascending order
// create a course parallel array to print out table showing
//   course and mark assigned along with overall average

// ASSIGNMENT : Find the highest mark
// : in this version of the marks program you will visit the following website :
// and read the section on Arrays (Sequential
// Search) and develop an algorithm to find the highest mark in your grades array

public class Marks3 {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// declares an array of integers
        int[] grades;

        // allocates memory for 4 integers marks
        grades = new int[4];
        double total = 0;
        // must initialize accumulator
        //int MaxValue;
        int maxValue = grades[0]; 
        for (int g=0;g < 4;g++){
        	String mark = JOptionPane.showInputDialog("Enter mark " + g);
        	int grade = Integer.parseInt(mark);
        		// changing the seat picked to and integer
        	grades[g] = grade;
        	    // store marks into the grades array or list
        	total = total + grades[g];
    		for(int i=1;i < grades.length;i++){   
    		 if(grades[i] > maxValue){   
    		    maxValue = grades[i];   
    			System.out.println("Current max is " + maxValue);// TRACING technique
    	     }// end if   
    	    }// end for   
    		// soln:
        }// end for
		double average = total/4;
		System.out.println("The average is " + average);
		//display the results 
		JOptionPane.showMessageDialog ( null, "The average is " + average); 
		System.out.println("The max value in the array " + maxValue);
		System.exit ( 0 ); //ends the program 
		// validation :

	}// end main
}//end class

In the program listing above, you will note more emphasis on GUI, documentation of online research, finding a max value algorithm, parsing from GUI window (ex. int grade = Integer.parseInt(mark);). Students respond well to the marks program because they are familiar with grades and like to test their own values. In addition, this lab moves from a “known to unknown” continuum and by the end of the sequence we have covered a number of topics and removed the confusion of object-oriented design.

Task 2

Revise the Marks3 program to calculate the minimum value in the list. Add a bubble sort method to sort the list in descending order. Save the new class as Marks4.

Stage 2 : Inheritance

After completing the Marks programming activity we will get back to objects. It would be a good time to introduce the concept of inheritance. Earlier we discussed abstraction and encapsulation and now it is time to discuss another tenant of OOP, inheritance. I found a fantastic lab in the text, “A Guide to Programming in Java, Second Edition” (EMC Publishing) that does a great job of introducing inheritance. It is the Circle -> Disk -> Puck sequence of labs. However, in this tutorial we will start our study of inheritance with the Dog class.

Students respond well to the Dog lab because they know what a dog is and can contribute to the building of the model. Here is an example of the Dog class:

public class Dog {
	private String name;
	private int weight;
	public Dog(String name, int weight){
		// constructor is empty for now = name;
		this.weight = weight;
	public void barks(int numtimes){
		for (int i=0;i < numtimes;i++){
			System.out.println("Woof, Woof!!!");
		}// end for
	}// end barks
	public String getName(){
		return name;
	public double getWeight(){
		return weight;
	public String toString() {
		String dogString;

		dogString = "Dog has name " + + " and weighs " + this.weight;

}// end class

When designing the Dog class we discuss the “nouns” or instance variables and the “verbs” or methods or what the object can do. Here is a UML diagram of our Dog class:

- name : String - weight: int
+ Dog() -> constructor + void barks + void setAge + getName + getWeight + toString()

Next, we want to use inheritance to create another type of dog that will inherit everything dog currently has but add a few new features. The new object will take less time to develop because we are reusing existing code to create the new object. The new dog will be a PoliceDog. What can a police dog do that is different from normal dogs?


Here is an example of the PoliceDog class:

public class PoliceDog extends Dog {
	private boolean smell;

	public PoliceDog() {
		// TODO Auto-generated constructor stub
		super("Bon Nez", 54);  // construct Dog and have access to member methods
		this.smell = false;
	public void smellDope(boolean smell){
		if (smell == true){           // need double equals for boolean
			System.out.println("Grrrrr!  Doggy smells dope");
		}else {
			System.out.println("Ruff! Ruff! Nothing here!");
		} // end if
	}// end smellDope
	public String toString() {
		// we override toString to reflect new dog
		String policedogString;

		policedogString = "The Police Dog has name " + super.getName() + " and weighs " + super.getWeight() + " The value of smell boolean variable = " + this.smell;

}// end class

In the PoliceDog source code listed above you will note how the “extends” keyword is used to inherit all instance variables and methods belonging to the Dog class. We use the “super” keyword to create our new dog from the superclass Dog. Note that the constructor in Dog matches the number of parameters used in “super” statement. To create the PoliceDog we simply add new instance variables to complement what is included by “super” and add methods required by a police dog. In this example, the Dog class is the superclass or base class and the PoliceDog class is the subclass. I think you can see that inheritance would be a very useful tool in game design or where there are slight variations in the objects used by the software. For example, imagine how a company that sells tires might use inheritance to develop object-oriented solutions for managing inventory or how a boat retailer can differentiate between different types of crafts by using inheritance.


We need a “driver” class to test out Dog and PoliceDog classes:

import java.util.Scanner;

public class UseDog {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Dog d = new Dog("K-DOG", 23);
		if (d.getName().equals("K-DOG")){
			System.out.println("You rock Brother!!");
		}// end if
		System.out.println("How many barks?");
		Scanner nb = new Scanner(;
		int numbarks = nb.nextInt();
		PoliceDog pd = new PoliceDog();
		// System.out.println(pd.toString()); tracing toString()
		Dog d2 = new PoliceDog();  // polymorphism example : example of CASTING
		// System.out.println(d2.);  // d2 does not have access to smellDope
									// cannot run subclass cast of PoliceDog d3 = new Dog()



Task 3

Develop a UML and write your own CircusDog class using inheritance.

Bigger more extensible and flexible software design

Once you get out of the “main” in Java and you are comfortable with object –oriented concepts you can move onto bigger more complex software design projects. Your ability to create more extensible and maintainable projects will depend on your grasp of inheritance, composition, polymorphism, abstract classes, casting (up/down) and interfaces. These big words and design techniques will give you maximum flexibility and code reuse when creating more complex programs. The next step after this would be to study design patterns which is not the focus of this tutorial.

Stage 3 : Polymorphism, Interfaces, abstract classes

The purpose of polymorphism is to separate implementation from interface. We can decouple class relationships by using the derived class to refer to the base or superclass. This process is known as upcasting and can make our programs more flexible and extensible. It means that we can change our programs without a lot of additional code. Polymorphism means “many forms” and can use a supertype to refer to derived classes. It is made possible by “dynamic binding” or late binding or run-time binding which is a feature of contemporary object-oriented languages (ex. Java, C++, C#).

The devil here is in the details. We want to write a program that works with different shapes; circle, rectangle, etc. Therefore, through abstraction we note that these are all Shapes and we can design a base class Shape (best if it is abstract) and use inheritance to build all the other types or derived classes.

Polymorphism enables a derived class or subclass to work directly with the superclass or in code allows the supertype reference type to work with a derived object:

Shape s = new Circle();

The line above demonstrates the idea of decoupling or separating implementation from interface. Some will call this the polymorphic substitution principle. Note that the class reference type (ex. Shape) is NOT the SAME as the object (ex. Circle). Most of us when we start programming in Java will write programs that implement or instantiate an object as follows:

Dog d = new Dog();

In the line above you will note that the class reference type is the SAME as the object.

UML view of object hierarchy in Shapes example - importance of inheritance in polymorphism Fig ref: Thinking in Java, 4th Edition

Okay, so you have some understanding of polymorphism. Next, we will look at another way to expand your object-oriented design skills by using interfaces. By all accounts on the Internet and in text books, it appears that interfaces are very important if you wish to write more extensible and flexible code. For one thing a class can implement multiple interfaces which will allow for “multiple inheritance" which is NOT permitted in Java using the conventional “extends” keyword.

When using an interface in Java you will use the key word “implements” to access the abstract methods. Interfaces are abstract by default. You may have seen the use of “implements” in the past when working with files, animation or graphics. For example, you may have implemented Serializable, Runnable and JFrame as interfaces to expand a program’s capability.

In the working example below, we will cut and paste code to the appropriate class names to see how polymorphism, interfaces and abstract classes work together to provide a powerful framework for building more elaborate Java programs.

DEMO of polymorphism, interfaces and abstract classes working together

UML view of object hierarchy in ploymorhism interface absctract class demo Fig ref :
interface : save as

public interface Walk {
	String walk ();
	// all methods in an interface are abstract


abstract class

public abstract class Animal implements Walk{
	abstract String MakeNoise();
	// note the use of key word "implements"


Dog extends Animal abstract class and implements Walk

public class Dog extends Animal{
	// hover over Dog and Eclipse invites you to add 
	// unimplemented methods =>  @Override added automatically

	public String walk() {
		// TODO Auto-generated method stub
		return "dog is walking";
		// change "null"to appropriate values

	String MakeNoise() {
		// TODO Auto-generated method stub
		return "bark";
		// we must include all abstract methods found in Animal and 
		// override them with new and appropriate values or "response" :)


Cat extends Animal abstract class and implements Walk

public class Cat extends Animal{

	public String walk() {
		// TODO Auto-generated method stub
		return "cat is walking";

	String MakeNoise() {
		// TODO Auto-generated method stub
		return "Meow";


Human is just another object on its own

public class Human {
	public void Speak(){
		System.out.println(".... Speaking human English....");


The MainClass or driver for the demo

import java.util.Random;

public class MainClass {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Random randomGen = new Random();
		Animal[] zoo = new Animal[4];
		zoo[0]= new Dog();
		zoo[1]= new Cat();
		zoo[2]= new Cat();
		zoo[3]= new Dog();
		for (Animal animal : zoo){
			if (animal instanceof Dog){
				Dog kdog = (Dog)animal; // manual downcasting?
		}// end if
		}// end for
	for (Animal animal2 : zoo){
			System.out.println(animal2.walk());  // from abstract interface
	}// end for
	// example of a polymorphic array
	}// end main
}// end class

// ref:

// ref (casting):
// ref (up and downcasting):

// ref : interfaces :

Stage 4 : Composition : Pizza Program

define: object composed of other objects

Composition or aggregation involves a HAS-A relationship. For example, a Line has-a Point, a Pizza Order has-a Pizza, a Car has-a Motor and so on. Many programmers prefer using composition to inheritance because the has-a relationship works best for their project needs. If you take time to assemble the Java 2D game code, you will see how composition is used to add elements to gaming world or canvas. You will start to understand how classes can be used to assemble the parts to make up the whole.

ref: Point and Line example : Point and Line

ref: Java 2D game design : Collision : Java 2D game

- Note: you will need to set up a "package" in your Eclipse project called "collision" and save all five classes from the Java 2D game website into the package folder. In addition, you will need to add the three sprites to same folder along side the Java classes (ex.,,, etc).

//: reusing/
// Composition with public objects.
class Engine {
public void start() {}
public void rev() {}
public void stop() {}

class Wheel {
public void inflate(int psi) {}

class Window {
public void rollup() {}
public void rolldown() {}

class Door {
public Window window = new Window();
public void open() {}
public void close() {}

public class Car {
public Engine engine = new Engine();
public Wheel[] wheel = new Wheel[4];
public Door
left = new Door(),
right = new Door(); // 2-door
public Car() {
for(int i = 0; i < 4; i++)
wheel[i] = new Wheel();

public static void main(String[] args) {

Car car = new Car();

} // example from "Thinking in Java"

The Pizza Program - Demo of composition

The code listed below processes multiple pizza orders using an object-oriented design. The use of arraylists were necessary to create persistence in the program to process the multiple orders.

// A class which can create types of pizza
public class Pizza
	// private variables for each pizza
	private String name;
	private int size;
	private double price;
	// constructor - make a pizza
	public Pizza (String n, int s)
	{ = n;
		this.size = s;
		this.price = setPrice(size);
	// calculate a price based on size
	private double setPrice (int s)
		double p = 0.0;
		if(s == 1)
			p = 10.00; // small
		if(s == 2)
			p = 15.00; // medium
		if(s == 3)
			p = 20.00; // large
		return p;
	} // end of private method

	public double getPrice()
		return price;
	public String getName()
		return name;
} // end of class

// This is the driver class managing user I/O
import java.util.Scanner;

public class OrderPizza

	static Scanner userInput = new Scanner(;
	// global scanner variable
	// variables needed
	private static Pizza ourPizza; // only variable 'object' needed
	private PizzaBill ourBill;  // OrderPizza HAS-A Pizza and PizzaBill = composition
	// Why is Pizza ourPizza now STATIC? = global variable
	// constructor for ordering Pizza
	public OrderPizza()
		ourPizza = null;
		ourBill = null;

	// helper methods
	private void printBill()
		ourBill = new PizzaBill(ourPizza);


	private void getOrder()
		Scanner userInput = new Scanner(;
		int choice = 0;
		System.out.println("small -1- medium -2- large -3-");
		choice = userInput.nextInt();
		// build our pizza
		if(choice == 1)
			ourPizza = new Pizza("small", 1);
		if(choice == 2)
			ourPizza = new Pizza("medium", 2);
		if(choice == 3)
			ourPizza = new Pizza("large", 3);
	} // end of get method
	public static void main(String[] args)
		OrderPizza op = new OrderPizza();
		PizzaBill pb = new PizzaBill(ourPizza);
		System.out.println("How many pizzas would you like to order?");
		int numpizza = userInput.nextInt();
		for (int i=1;i <= numpizza;i++){;
		}// end for
	} // end of main method
	// Method that calls helper methods - add numorders for multiple
	public void run(int numorders)
} // end of class

import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

// This is a simple bill class

public class PizzaBill
	// needed object variable
	private Pizza ourPizza;
	static ArrayList totals = new ArrayList();
	static ArrayList pnames = new ArrayList();
	static ArrayList taxtotals = new ArrayList();
	static ArrayList pricetotals = new ArrayList();
	// solved by Mark Regush
	public PizzaBill ( Pizza p )
		ourPizza = p;
	// calulates the tax owed - helper method
	private double taxCalc()
		double owed = 0.15 * ourPizza.getPrice();
		return owed;
	// finds the total - interface method
	public double getTotalCost()
		double totalCost = ourPizza.getPrice() + this.taxCalc();
		return totalCost;
	// primitive formatting string method
	public String getBill()
		String text = "------------BILL------------\n";
		text += "*********    Royals Pizza ************\n";  
		text += "Date : " + this.getDateNow() + "\n";  
		text += "You Orderd a " + ourPizza.getName()+ "\n";
		text += "Subtotal: $" + ourPizza.getPrice() + "\n";
		text += "Taxes: $" + this.taxCalc() + "\n";
		text += "Total Price $" + this.getTotalCost() + "\n";
		text += "----------------------------\n";
		return text;
	// added date code to bill - June 2012
	// added libraries to top
	public String getDateNow (){
	  Calendar currentDate = Calendar.getInstance();
	  SimpleDateFormat formatter= 
	  new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
	  String dateNow = formatter.format(currentDate.getTime());
	  // System.out.println("Now the date is :=>  " + dateNow);
	  return dateNow;
	// source : changed class to method :
	public void finalBill(){
		double finaltotal = 0;
		double finalprice = 0;
		double finaltax = 0;
		String finalname = "";
		for (int i=0; i < totals.size();i++){
			finaltotal += totals.get(i);
		for (int i=0; i < taxtotals.size();i++){
			finaltax += taxtotals.get(i);
		for (int i=0; i < pricetotals.size();i++){
			finalprice += pricetotals.get(i);
		for (int i=0; i < pnames.size();i++){
			finalname += pnames.get(i);
		String text = "------------FINAL BILL------------\n";
		text += "*********    Royals Pizza ************\n";  
		text += "Date : " + this.getDateNow() + "\n";  
		text += "You Ordered " + finalname + "\n";
		text += "Subtotal: $" + finalprice + "\n";
		text += "Taxes: $" + finaltax + "\n";
		text += "Total Price $" + finaltotal + "\n";
		text += "----------------------------\n";
	}// end finalBill
}// end of class

The Big Task

connecting Java objects to data

Team Batting Average

Write a computer program to calculate a baseball team’s overall batting average. Your program will print out a 4 column table with appropriate headings to show each individual player’s name, hits, number of times at bat and batting average followed by the team’s overall average. All player information is stored in a comma delimited text file named “teamstats.txt”. The database features player name, hits and times at bat. The structure of the database would look as follows:


Parse file to access records and fields encapsulated in the object



hits : int
atbats: int
name : String

In mySQL, you would have to assign a length to each of the fields found in the database. For example, name may require 20 characters, hits 3 and atbats 3. Therefore, each record would use up 26 characters in storage. In our example, we will store data in a comma delimited flat text file and will appear as follows:

Pete Rose, 46, 80
Tim Peters, 3, 20

The above problem is a typical procedural programming task that can be solved easily in QBASIC, VB or Python. However, it becomes more daunting if you want to use object-oriented design and Java. The first step is to restate the problem using OO design which means starting with abstraction and identifying the objects.

What real-world objects do we visualize when reading the team batting average problem? I see a baseball player and a team to start. Okay, now we will create a Java project called “Team Batting Average” with two objects: Player and FileReader. The Player object is our model and will be the blueprint for managing the data and the FileReader class will contain file handling, parsing and program logic to generate desired output.

public class Player{  
private double hits;   
private double atbats;   
private String name;   
        /**constructor creates the object with encapsulated hits, atbats and name values that cannot be changed*/  
        public Player(double xhits, double xatbats, String xname) {   
            this.hits = xhits;   
            this.atbats = xatbats;   
   = xname;   
public double gethits() {   
return hits;   
public double getatbats() {   
return atbats;   
public String getname() {   
return name;   

public double batave(double hits, double atbats){
	return this.gethits()/this.getatbats();
} // added July 27 - works

public String toString(){
	String playerInfo;
	playerInfo = getname() + " has " + gethits() + " hits " +
	" with " + getatbats() + " at bats." + "Batting Ave = " + batave(gethits(),getatbats());
	return (playerInfo);
	// created toString on July 27, 2012 for ACSE
}// end toString
} // end Player class

Once we have built the Player object or file then we can consider how to manilate the data found in teamstats.txt to generate the desired output or team batting average. In addition, we can use loops, decision and arraylists to generate some team statistics and empower us to use data more often when developing rich programming experiences.

In the FileReader class, we use parsing to build live instantiated Player objects and we store these records into an arraylist called dbstats for further processing. We can manipulate each Player object while inside the while loop and we can test data persistence outside of the loop by printing out contents of the arraylist. I believe this lab is good for students and teachers that want to explore game programming because from my research preserving game state through persistence and serialization is critical to program design.

Let’s look at the FileReader class and observe how it connects data to our live instantiated objects. I have included a lot of tracing in the program listing to show you how the data processing works:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;   
//import javax.swing.*;
class FileReader   
public static void main(String[] args) throws IOException
	int countpoorbatters = 0;
	double teamtotal = 0;   // accumulator for team average calculation
	File file = new File("teamstats.txt");
	List dbstats = new ArrayList();
	//create an arraylist to store live Player objects for processing

try {
	Scanner scanner = new Scanner(file);
	// use Scanner to parse database

	// used hasNextLine because it manages all type of data
	// which includes numeric and string

while (scanner.hasNextLine()) {
	String line = scanner.nextLine();

	Scanner lineScanner = new Scanner(line);
	// second Scanner focuses on data and tokens

	double xhits = lineScanner.nextDouble();
	double xatbats = lineScanner.nextDouble();
	// forced to change all var declarations to double
	// to satisfy the average calc - must do same in Player class
	String xname =;

	Player record = new Player(xhits,xatbats,xname);
	// linking data with "live" instantiated object = OO data processing
	teamtotal = teamtotal + record.batave(record.gethits(), record.getatbats());
	// use the above outside of loop to print final output
	System.out.println(xhits + " " + xatbats + " " + xname); // tracing
	System.out.println(record);  // will run toString method : July 27

	System.out.println(xname + "is a good guy"); // testing data from Scanner
	System.out.println(xhits * 3);
	System.out.println(xatbats * 2);
	double av = (xhits/xatbats);  // fixed average calc Feb. 15, 2012
								// -> changed int to double
	System.out.println(xname + " has a batting average = " + av);

	if (av > .300){
		System.out.println("Way to go slugger!");
		System.out.println("Back to the cage!");
		countpoorbatters = countpoorbatters + 1;
	}// end if


	// uses methods from the Player class

	System.out.println("inside loop");
}// end while

System.out.println("outside loop");

 catch (FileNotFoundException e) {
}// end try

	int n = dbstats.size();
	for(int i = 0; i < n ; i++){
	  System.out.println( "Test 1 : " + dbstats.get( i ) );
	} // end for
	for (Player p:dbstats){  // change type to Object and it works : Object should be Person : both work
		System.out.println("Test 2: " + p);
	// trying to iterate through arraylist to find a specific player
	// need to research use of arraylist
	// code :

	System.out.println("Number of batters going to the cage = " + countpoorbatters);
	System.out.println("Total number of players in db = " + dbstats.size());
	System.out.println("Team Average = " + teamtotal/dbstats.size());
}// end main
}// end FileReader class

Useful references

Big Java, 4th Edition by Cay Horstmann

A Guide to Programming in Java, 3rd Edition, Jan Marrelli

Head First Java, 2nd Edition