Hello and welcome back to the Kotlin bookkeeping project.

In this chapter, we will create a java class which will read the number of students that need to buy the Kotlin-related book from a text file and then return that number which will then be used in the for loop in the main program which we have created in the previous chapter.

First of all, we will create a text file with a number which indicates the total students that need the Kotlin-related book.

create a count.txt file with the number of students that need to buy the Kotlin-related books.

We will then create a simple java reader class which is the subclass of the java FileReader class.

import java.io.FileReader;
import java.io.IOException;

public class Reader extends FileReader {
    private int student_count;
    public Reader(String fileName) throws IOException {
        super(fileName);
        int i;
        while ((i=this.read()) != -1)
            student_count = Character.getNumericValue(((char)i));
    }

    public int getStudent_count() {
        return student_count;
    }
}

This class will first read the student numbers from the text file and then return that number to the caller program which is in the Kotlin main file.

Finally we just use that java class like any Kotlin class in the main Kotlin program.

fun main(args : Array<String>) {

    FilterBook.sale_tax = 1.029
    //FilterBook.calculate_total_price(book = mapOf("Kotlin" to 20.00, "Kotlin is really great" to 10.00, "Other Program" to 26.00, "Why Kotlin is really great?" to 40.00))
    FilterBook.calculate_total_price(KotlinBookTotalAmount)
    //val jimmy = Stdent1(FilterBook.total_purchase)
    //val tommy = Stdent1(FilterBook.total_purchase)
    //val george = Stdent1(FilterBook.total_purchase)
    val student_group = StdentGrouping()

    val reader = Reader("src/count.txt") // initialize the java reader class
    val count = reader.student_count // the total student number
    for(total_student in (1..count))
        student_group.includeStudentToGroup(Stdent1(FilterBook.total_purchase))
    student_group.calculateTotalAmount() // calculate the total amount of books
    //print("%.2f".format(jimmy.total_purchase + tommy.total_purchase + george.total_purchase)) // output 926.10
    student_group.printTotalAmount() // print total amount of books purchase by the student
}

As you can see, we no longer need to hard-code the count variable as before, we can change the number of students just by changing that number in the text file we have just created earlier.

Click to rate this post!
[Total: 0 Average: 0]
Please follow and like us:
error0

Leave a Reply

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