a real java program

A Real Java Program – Student Hostel Program

“A Real Java Program – Student Hostel Program” is simple kind of a commercial program which can be written in Java. The Program is designed for a student hostel with 100 rooms that can record a new student and also records their payments for the rent.  The Program is originally a case study in Java In Two Semester book which was edited and re created by me.

The Program consists of 8 classes:

1- Tenant: Create a tenant with his/her name as well as his/her room number.

2-Payment: Create a payment for a particular tenant. It records the month and the amount which was paid by the tenant.

3-PaymentList: It’s a collection Java class which Inherits from ObjectList class and records the payment list (array) of all the payments by a tenant.

4- ObjectList: It’s a super class for PaymentList and TenantList and create a list(array) from the objects.

5-TenantList: It’s a collection Java class which Inherits from ObjectList class and records the tenants.

6-HostelGUI: It’s a the class for designing the interface of the program (GUI).

7-HostelProgram: It creates an object of HostelGUI class to execute the program.

8-TenantFileHandler: It’s a class to store entered data by user. (It’s taken from Java In Two Semester Book).

Tenant Class:


public class Tenant {
//Attributes
private String name;
private int room;
private PaymentList payments;
public static int maxNoOfPayments = 12;

//Methods
public Tenant(String nameIn, int roomIn) {
name = nameIn;
room = roomIn;
payments = new PaymentList(maxNoOfPayments);
}

public String getName() {
return name;
}

public int getRoom() {
return room;
}

public void makePayment(Payment paymentIn) {
payments.add(paymentIn);
}

public PaymentList getPayments() {
return payments;
}

public String toString() {
return name + ", " + room;
}

}

The Payment Class:


public class Payment {
//Attributes
private String month;
private double amount;

//Methods
public Payment(String monthIn, double amountIn) {
month = monthIn;
amount = amountIn;
}

public String getMonth() {
return month;
}

public double getAmount() {
return amount;
}

public String toString() {
return month + ", " + amount;
}

}

The ObjectList Class:


public class ObjectList {
//Attributes
private Object[] list;
private int total;

//Methods
public ObjectList(int sizeIn) {
list = new Object[sizeIn];
total = 0;
}

public boolean add(Object objectIn) {
if(!isFull()) {
list[total] = objectIn;
total++;
return true;
} else {
return false;
}
}

public boolean isEmpty() {
if(total== 0) {
return true;
} else {
return false;
}
}

public boolean isFull() {
if(total == list.length) {
return true;
} else {
return false;
}
}

public Object getItem(int indexIn) {
if(indexIn < 1 || indexIn > total) {
return null;
} else {
return list[indexIn - 1];
}
}

public int getTotal() {
return total;
}

public boolean remove(int indexIn) {
if(indexIn >= 1 && indexIn <= total) {
for(int i = indexIn - 1; i <= total - 2; i++) {
list[i] = list[i + 1];
}
total--;
return true;
} else {
return false;
}
}

public String toString()
{
String items = "";
for(int i =0; i < total; i++)
{
items = items + list[i].toString() + " ";
}
return "[ " + items +"]";
}

}

The PaymentList Class:


public class PaymentList extends ObjectList {
//Attributes

//Methods
public PaymentList(int sizeIn) {
super(sizeIn);
}

public Payment getPayment(int monthIn) {
if(monthIn < 1 || monthIn > getTotal()) {
return null;
} else {
return (Payment) getItem(monthIn);
}
}

public double calculateTotalPaid() {
double totalPaid = 0;
for(int i = 1; i <= getTotal(); i++) {
totalPaid += getPayment(i).getAmount();
}
return totalPaid;
}

}

The TenantList Class:


public class TenantList extends ObjectList {

//methods
public TenantList(int sizeIn) {
super(sizeIn);
}

public Tenant getTenant(int positionIn) {
if (positionIn<1 || positionIn>getTotal()) {
return null;
} else {

return (Tenant) getItem(positionIn);
}

}

public Tenant search(int roomIn) {
for (int i = 1; i <= getTotal(); i++) {
if(getTenant(i).getRoom() == roomIn) {
return getTenant(i);
}
}
return null;
}

public boolean removeTenant(int roomIn)
{
for(int i = 1;i <= getTotal();i++)
{
if(getTenant(i).getRoom() == roomIn)
{
remove(i);
return true;
}
}
return false;
}
}

The HostelGUI Class:



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.text.*;

/**This is a GUI class for the Student hostel Program.
*
* @author Parham Majdabadi
*
*/
public class HostelGUI extends JFrame implements ActionListener {
// Attributes
private JTextField roomField = new JTextField(5);
private JTextField nameField = new JTextField(38);
private JButton addTenant = new JButton("Add Tenant");
private JButton displayTenants = new JButton("Display Tenants");
private JButton removeTenant = new JButton("Remove Tenant");
private JButton saveAndQuit = new JButton("Save and Quit");
private JButton quitWithoutSaving = new JButton("Quit Without Saving");
private JTextArea tenants = new JTextArea(10,45);
private JTextField room1Field = new JTextField(5);
private JTextField monthField = new JTextField(7);
private JTextField amountField = new JTextField(7);
private JButton makePayment = new JButton("Make Payment");
private JButton listPayments = new JButton("List Payments");
private JTextArea payments = new JTextArea(10,45);
private int numberOfRooms;
private TenantList list;

/**The constructor for the class
* @param number of Rooms
* @return Create an object of HostelGUI class
*/
public HostelGUI(int numberOfRoomsIn) {
setTitle("Student hostel Software");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(550,600);
setLocation(100,100);
getContentPane().setBackground(Color.LIGHT_GRAY);
//adding components to canvas
roomField.setBorder(new TitledBorder("Room"));
add(roomField);
nameField.setBorder(new TitledBorder("Name"));
add(nameField);
add(addTenant);
add(displayTenants);
add(removeTenant);
add(saveAndQuit);
add(quitWithoutSaving);
tenants.setBorder(new TitledBorder("Tenants"));
JScrollPane scroll1 = new JScrollPane(tenants);
add(scroll1);
room1Field.setBorder(new TitledBorder("Room"));
add(room1Field);
monthField.setBorder(new TitledBorder("Month"));
add(monthField);
amountField.setBorder(new TitledBorder("Amount"));
add(amountField);
add(makePayment);
add(listPayments);
payments.setBorder(new TitledBorder("Payments"));
JScrollPane scroll2 = new JScrollPane(payments);
add(payments);
add(scroll2);
//adding the listeners to the buttons
addTenant.addActionListener(this);
displayTenants.addActionListener(this);
removeTenant.addActionListener(this);
saveAndQuit.addActionListener(this);
quitWithoutSaving.addActionListener(this);
makePayment.addActionListener(this);
listPayments.addActionListener(this);
setVisible(true);
numberOfRooms = numberOfRoomsIn;
list = new TenantList(numberOfRooms);
//read records from file
TenantFileHandler.readRecords(list);
}

public void actionPerformed(ActionEvent e) {
if(e.getSource() == addTenant) {
String name = nameField.getText();
int room = Integer.parseInt(roomField.getText());

if(nameField.getText() == "" || roomField.getText() == "") {
tenants.setText("Room number or Name cannot be blank");
} else if(room < 1 || room > numberOfRooms) {
tenants.setText("Invalid room number!");
} else if(list.search(room) != null) {
tenants.setText("The Room has already been taken!");
} else {
Tenant myTenant = new Tenant(name,room);
list.add(myTenant);
roomField.setText("");
nameField.setText("");
tenants.setText("Mr/Miss " + name + " with room number " + room + " has been added!");
}

}
if(e.getSource() == displayTenants) {
if(list.isEmpty() == true) {
tenants.setText("All the rooms are empty!");
} else {
tenants.setText("Room" + "t" + "Name" + "n");
for(int i = 1; i <= list.getTotal(); i++ ) {
tenants.append(list.getTenant(i).getRoom() + "t" + list.getTenant(i).getName() + "n");
}
}
}
if(e.getSource() == removeTenant) {
int room = Integer.parseInt(roomField.getText());
if(roomField.getText() == "") {
tenants.setText("Please enter a room number!");
} else if(list.search(room) == null) {
tenants.setText("There is not such a room!");
} else if(room < 1 || room > numberOfRooms) {
tenants.setText("Invalid Room number!");
} else {
list.removeTenant(room);
tenants.setText("The Tenant wih room number " + room + " has been removed successfully");

}
}
if(e.getSource() == saveAndQuit) {
TenantFileHandler.saveRecords(numberOfRooms, list);
System.exit(0);
}
if(e.getSource() == quitWithoutSaving) {
System.exit(0);
}
if(e.getSource() == makePayment) {
int room = Integer.parseInt(room1Field.getText());
int month = Integer.parseInt(monthField.getText());
double amount = Double.parseDouble(amountField.getText());
if(room < 1 || room > numberOfRooms) {
payments.setText("Invalid Room number!");
} else if (room1Field.getText() == "" || monthField.getText() == "" || amountField.getText() == "") {
payments.setText("Room, month or amount cannot be blank");
} else if(amount < 0) {
payments.setText("amount must be a positive number!");
} else if(list.search(room) == null) {
payments.setText("There is no such a tenant with room number " + room);
} else {
DecimalFormat df = new DecimalFormat("#.##");
String amountString = df.format(amount);
amount = Double.parseDouble(amountString);
Payment myPayment = new Payment(monthField.getText(),amount);
list.search(room).makePayment(myPayment);
payments.setText("The payment has been recorded successfully!");
}
}
if(e.getSource() == listPayments) {
int room = Integer.parseInt(room1Field.getText());
if(room1Field.getText() == "") {
payments.setText("Please enter a room number");
} else if(room < 1 || room > numberOfRooms) {
payments.setText("Invalid Room Number");
} else if(list.search(room) == null) {
payments.setText("There is no tenant in the room");
} else {
Tenant myTenant = list.search(room);
PaymentList myPayment = myTenant.getPayments();
if(myTenant.getPayments().getTotal() == 0) {
payments.setText("There is no record of payment for the tenant");
} else {
payments.setText("Month" + "tt" + "Amount" + "n");
for(int i = 1; i <= myPayment.getTotal(); i++) {
payments.append("" + myPayment.getPayment(i).getMonth() + "tt" + " £" + myPayment.getPayment(i).getAmount() + "n");
}
DecimalFormat df = new DecimalFormat("#.##");
String totalAmount = df.format(myPayment.calculateTotalPaid());
payments.append("n" + "Total paid sor far: " + "£" + totalAmount);
monthField.setText("");
amountField.setText("");
room1Field.setText("");
}
}
}
}

}

The TenantFileHandler class:


import java.io.*;

class TenantFileHandler
{
public static void saveRecords(int noOfRoomsIn, TenantList listIn)
{

try
{
FileOutputStream tenantFile = new FileOutputStream("Tenants.dat");
DataOutputStream tenantWriter = new DataOutputStream(tenantFile);
tenantWriter.writeInt(listIn.getTotal());
for(int i=1; i <= noOfRoomsIn; i++)
{
if(listIn.getTenant(i) != null)
{
tenantWriter.writeInt(listIn.getTenant(i).getRoom());
tenantWriter.writeUTF(listIn.getTenant(i).getName());
tenantWriter.writeInt(listIn.getTenant(i).getPayments().getTotal());
for(int j = 1; j<= listIn.getTenant(i).getPayments().getTotal(); j++)
{
tenantWriter.writeUTF(listIn.getTenant(i).getPayments().getPayment(j).getMonth());
tenantWriter.writeDouble(listIn.getTenant(i).getPayments().getPayment(j).getAmount());
}
}
}
tenantWriter.flush();
tenantWriter.close();
}
catch(IOException ioe)
{
System.out.println("Error writing file");
}

}

public static void readRecords(TenantList listIn)
{

try
{
FileInputStream tenantFile = new FileInputStream("Tenants.dat");
DataInputStream tenantReader = new DataInputStream(tenantFile);

int tempRoom = 0;
String tempName = new String("");
String tempMonth = new String("");
double tempAmount = 0 ;
Tenant tempTenant = null;
Payment tempPayment = null;
int tot = 0;
int totpay = 0;

tot = tenantReader.readInt();
for(int j = 1; j<=tot; j++)
{
tempRoom = tenantReader.readInt();
tempName = tenantReader.readUTF();
tempTenant = new Tenant(tempName,tempRoom);
totpay = tenantReader.readInt();
for(int k = 1; k <= totpay; k++)
{
tempMonth = tenantReader.readUTF();;
tempAmount = tenantReader.readDouble();
tempPayment = new Payment(tempMonth, tempAmount);
tempTenant.makePayment(tempPayment);
}
listIn.add(tempTenant);

}
tenantReader.close();
}

catch(IOException ioe)
{
System.out.println("No records found");
}

}
}

The HostelProgram class:


public class HostelProgram {

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

}


Leave a Reply

Your email address will not be published. Required fields are marked *