COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Arrays ArrayProcessing.java BookRating.java BookRatingWithFileIO.java Book Rating OOP Program
Book.java
BookRatingClient.java
Array of Objects Program
City.java
CityClient.java




BookRatingWithFileIO Program


Description

An external data file BookRating_Data.txt contains the book rating information for a number of books.

This is program is similar to the previous program, but the book's information is stored in the data file and the number of books is unknown.

The program uses two arrays to store title and rating for a number of books, and uses several methods to do the following:

Determine the number books in the data file

Fill in the arrays with the data in the date file

Calculate the average rating

Find the the book with the highest rating (assume there is no tie)

Print books title and rating

Associated Concepts:

Array

File Input / Output

Algorithm:

main method:

Call method to determine the number of books in the data file

Based on the number of books, create two arrays to store books information

Array of String to store titles

Array of double to store ratings

Call methods to:

Read data in the data file to populate the arrays

Print the array elements

Calculate the total rating

Find the index of the book with the highest rating (assume there is no tie) and print the result

Print the average rating

countBooks method definition:

Declare variable count and initialize it to 0

Read the top line of data without storing it

while loop: as long as the data file has data item

Read the entire line of data without storing it

Increment count

populateArray method definition:

Read the top line of data without storing it

Declare variable i and initialize it to 0

while loop: as long as the data file has data item

Read title and rating from the data file

Assign them to the array cell i

Increment i

printArray method definition:

For i = 0 to last index of array cell

Print the array elements at i

sumArray method definition:

Declare variable sum and initialize it to 0

For i = 0 to last index of array cell

Add the current rating at i to sum

return sum

indexOfHighestRating method definition:

Declare variable maxIndex and assign it to 0 (Assume the first element is the highest)

For i = 1 to last index of array cell

If the current element at i is greater than the current highest element

    Update maxIndex to the current index i

return maxIndex

Source Code



Input File BookRating_Data.txt:



Sample Run



Video