Library Fine Program in Java

Library Fine Program in Java. City Library Fine Report in Java. The user details are given in the file, read that file, get the days, calculate the fine, and store the fine amount and username in a separate file.

Description:- City Library Fine Report in Java

The City Library is planning to computerize their work in order to provide an efficient service. As the first step, you are asked to create a system that can be used to handle the report generation of the Library, specifically to calculate and generate the reports for fining details for each user. Create a new Project named S16xxxQ1 for the library fine program in Java and implement the functionality described below.

a. Create a method to read data from the fine “fineDetails.txt” stored in your home (D:/) drive and store the data using a suitable data structure. Two sample rows of the data are given below.

User NameBook NameNo of Days (Late)
EmilyThe Bourne Identity5
MichaelThe List15

Note:- Actual text file (fineDetails.txt) contains comma-separated data fields. ↓ Download the fineDetails.txt file.

File “fineDetails.txt” contains,

Emily,The Bourne Identity,5
Michael,The List,15
Jacob,Lord of the Rings,8
Emma,Twilight-New Moon,25
Sarah,Stormlight Archive,2
Grace,Tower of Darkness,20
Jack,Tangled,9
Alexis,Last Sacrifice,13
Jasmine,Third Twin,11
Eric,The Goblet of Fire,25

b. Create another method that can be used to calculate fines for each user and write them to a file named fineReport.txt. The calculation details are as follows.

Fine Period- After return dateFine Amount
First week (from day 1 until day 7)$1 per day
Second week (from day 8 until day 14)$3 per day
After second week$5 per day

Example:-

Fine for Emily => 5 * 1 = 5/-
Fine for Michael => (7 * 1) + (7 * 3) + (1 * 5) = 33/-

Output format

The output format of Java Library Fine Program should be written as follows:-

Emily,5
Michael,33
Jacob,10
Emma,83
Sarah,2
Grace,58
Jack,13
Alexis,25
Jasmine,19
Eric,83

Solution for Library Fine Program in Java

In Order to read character/text data from a file line by line, the BufferedReader class gives high performance compared to other classes. Similarly, the PrintWriter class gives better performance in order to write character/text data to a file. Therefore, we will use BufferedReader and PrintWriter classes in this example.

To store the user values we use the ArrayList collection. We will create a separate user class that will represent each user given in the file.

Note:- Complete code is given at last.

Create user class

First, let us create a user class having properties:- username, book-name, and late days. Provide a constructor to initialize the values. Since we need to get late days for the fine calculation purpose, and username to store in the final report, therefore, provide a getter method to access them.

// User.java
public class User {

  // User properties
  private String username;
  private String book;
  private Integer days;

  // constructor
  public User(String username, String book, Integer days) {
    this.username = username;
    this.book = book;
    this.days = days;
  }

  // important getter methods required in test class
  public String getUsername() {
    return username;
  }
  public Integer getDays() {
    return days;
  } 
}

How to read input from the file?

In Java, BufferedReader class is the most enhanced way to read the character or text data from the file/keyboard/network. BufferedReader itself directly can’t connect to a file/keyword, to connect to a file it can take the help of FileReader class, and to connect to the keyword it can take the help of InputStreamReader class. Read more about BufferedReader class in Java.

//  BufferedReader class object to read input from the file
// fineReport.txt located in D drive.
BufferedReader br = new BufferedReader(
                    new FileReader("D:\\fineReport.txt"));

The separators are platform-dependent. To separate the parent and child directory in Windows we use file separators “\”, but in the java program to represent “\” we need to use the escape sequence character “\\”. In windows we must use “\\”, and in Linux, we must use “/”. The above code is valid only for Windows operating system. See more about File object creation with complete file or directory path and File Separator.

In BufferedReader class we have the readLine() method which can read one line at a time. In our example, one line contains the username, book-name, and late date separated by a comma. Therefore, read one line and split it from comma(,).

// read one line
String line = br.readLine();
// seperate it from comma
String str[] = line.split(",");

Now, the line is separated into three parts and stored in the array of Strings. For example, it will split the “Michael,The List,15” line as,

str[0] = "Michael";
str[1] = "The List";
str[2] = "15";

Currently, all these values are in String format. But the “15” represents the late days therefore it should be converted from String to int value.

int days = Integer.parseInt(str[2]);

How to store data?

To store data, we can use the ArrayList class. Advantages of using ArrayList collection instead of an array:- Array has a size limitation, and we need to specify the array-size while creation of array object. But ArrayList is dynamically growable, without size limitation, and no need to specify the size.

// ArrayList object creation to store User values.
ArrayList<User> user = new ArrayList<User>();

To store username=”Michael”, book=”The List”, and days=15 we can write the code as,

// adding values to ArrayList
user.add(new User("Michael", "The List", 15));

How to calculate the fine?

To calculate the fine, first, get the late days. Based on the condition write the logic to calculate the fine.

  • For late-day <= 7 then fine = days * 1;
  • For late-day > 7 and <= 14 then fine = (fine for first 7 days) + (days-7)*3
  • And for more than 14 days fine = (fine for first 7 days) + (fine for next 7 days) + (days-14)*5

The above logic can be written as,

// loop to iterate the list
for (User usr : user) {

  // get late days
  days = usr.getDays();

  // calculate fine amount
  if(days <= 7)
    fine = days * 1;
  else if(days <= 14)
    fine = 7*1 + (days-7)*3;
  else
    fine = 7*1 + 7*3 + (days-14)*5;
} 

How to store the values in File?

In Java, the PrintWriter class is the most enhanced Writer to write character or text data to the file. The biggest advantage of PrintWriter over FileWriter and BufferedWriter is:- we can write any primitive data directly with or without a newline character, and methods of PrintWriter class never throw IOExceptions. Learn more about PrintWriter class in Java

// create PrintWriter object
PrintWriter pw = new PrintWriter("D:\\fineReport.txt");

The data will be saved in the file “fineReport.txt” in the D drive. If the file doesn’t exist then the constructor itself creates a new file, but the file with the same name and extension exists then it will override the file.

Assume we have a string “Michael” and an integer value 5 which should be inserted in the file then we can write it as,

// values which should to store
String name = "Michael";
int fine = 5;

// store the value in String form
pw.println(name+","+fine);

Note that the result will be stored in the String form, and they are separated by the line “\n” and each line will contain comma-separated values.


Code For Library Fine Program in Java

The project file structure in Eclipse IDE,

Project Structure - Library Fine Program in Java

Library Fine Program in Java

The User class,

// User.java
package com.kp.entity;
public class User {
  private String username;
  private String book;
  private Integer days;

  // constructor
  public User(String username, String book, Integer days) {
    this.username = username;
    this.book = book;
    this.days = days;
  }

  // important getter methods required in test class
  public String getUsername() {
    return username;
  }
  public Integer getDays() {
    return days;
  } 
}

Library class,

// Library.java
package com.kp.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;

import com.kp.entity.User;

public class Library {

  public static void main(String[] args) {
    // create list of User to store details
    ArrayList<User> user = new ArrayList<User>();
    try {
      // In this example fineDetails.txt is stored
      // at D drive (D:\) in Windows operating system.
      
      // read data from file and store in list
      read(user, "D:\\fineDetails.txt");

      // calculate fine and store in "fineReport.txt"
      calculateFine(user, "D:\\fineReport.txt");
      
      // display some message
      System.out.println("Fine report is saved.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // method to read data from the fine “fineDetails.txt”
  // stored in your home (H:/) drive
  // and store the data using a suitable data structure
  public static void read(ArrayList<User> user,
                       String string) throws Exception {
    // variables
    BufferedReader br = null;
    String line = null;
    String str[] = null;
    int days = 0;
    
    // create BufferedReader object
    br = new BufferedReader(new FileReader(string));

    // read till end of the file
    while (br.ready()) {
      // read one line
      line = br.readLine();

      // Split line by comma(,)
      str = line.split(",");

      // convert String to int (for days)
      days = Integer.parseInt(str[2]);

      // store details to ArrayList
      user.add(new User(str[0], str[1], days));
    }
    
    // close BufferedReader
    br.close();
  }

  // method to calculate fine and store in "fineReport.txt"
  public static void calculateFine(ArrayList<User> user,
              String string) throws Exception {
    // variables
    PrintWriter pw = null;
    int days = 0;
    int fine = 0;
    
    // create PrintWriter object
    pw = new PrintWriter(string);
    
    // loop to iterate the list
    for (User usr : user) {
      // get late days
      days = usr.getDays();
      
      // calculate fine amount
      if(days <= 7)
        fine = days * 1;
      else if(days <= 14)
        fine = 7*1 + (days-7)*3;
      else
        fine = 7*1 + 7*3 + (days-14)*5;
      
      // store values
      pw.println(usr.getUsername() + "," + fine);
    } 
    
    // close Stream
    pw.close();
  }
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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