0% found this document useful (0 votes)
2 views6 pages

Csci2081Lab6 Copy

CSCI 2081 Lab 6 focuses on Object-Oriented Programming, sorting, file I/O, and 2D arrays. Students will create a Bookshelf class to manage Book objects, implement sorting and file operations, and work with 2D arrays through a Matrix class. The lab includes milestones for testing methods, reading from and writing to files, and optional challenges for additional functionality.

Uploaded by

Natenael Tadele
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Csci2081Lab6 Copy

CSCI 2081 Lab 6 focuses on Object-Oriented Programming, sorting, file I/O, and 2D arrays. Students will create a Bookshelf class to manage Book objects, implement sorting and file operations, and work with 2D arrays through a Matrix class. The lab includes milestones for testing methods, reading from and writing to files, and optional challenges for additional functionality.

Uploaded by

Natenael Tadele
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSCI 2081 Lab 6

OOP, Sorting, File I/O, and 2D Arrays


1. Lab Rules
You are free to work alone or in teams of up to 3 people for this lab. The labs are designed so you can
complete them by the end of the lab period. To begin the lab, STOP and take 10 minutes to read
through the ENTIRE lab before you start typing. We also suggest you read the entire write-up
for a milestone before beginning work on that section. If you are unable to complete all of the
milestones by the end of the lab, you have until the last office hours on the Friday of the lab week
to get those checked off by any of the course TAs. We suggest you check off your milestones as soon as
you complete them, since Friday office hours can be busy. You will only receive credit for the
milestones you have checked off by a TA. There is nothing to submit to Canvas for this lab.

2. Attendance
Per the syllabus, students with 2 unexcused lab absences over the semester will automatically fail the
course. If you miss 2 labs without excuses, you are OK, but if you miss a third lab (without a
university-sanctioned excuse), you will fail the course. The TAs will take attendance during lab; we
expect students to be actively working on the lab material. Your presence in the lab is not sufficient to
be marked as present for attendance; you must arrive within the first 15 minutes and do at least some of
the lab (i.e., complete 3 milestones).

3. NOTE: To get checked off for any milestones for this lab, you must use an IDE such as
IntelliJ.

4. Introduction
As a college student, you may have read a lot of books (you might even own quite a few). For
this lab, we would like to use our computers to represent and search through numerous books.
To facilitate this, you have been provided with a Book class. It contains 3 private variables: a
title, an author, and a rating. It also contains getters, setters, a toString method, and a
compareTo method (we will get into that later).

1 Creating a Bookshelf Class

We will store our books in a Bookshelf class. Your Bookshelf will consist of an array of Book
objects, and it should also contain two constructors. One should not have any parameters and
should initialize the Bookarray with a default size of 20. The other should have one int
parameter, which will hold the size of the array. Optionally, you can also add a constructor that
accepts a reference to a Book array to use as the memberBook array. Your class should also
contain the following methods:

1
CSCI 2081 LAB 5

• public boolean add(Book newBook) – Attempt to add a Book to the first empty slot in
the Bookshelf. If it is successful, it should return true, otherwise return false. Do not allow
books to be added if the Bookshelf is full.

Hint: To maintain a constant (O(1)) time complexity, you may want a member
variable that keeps track of the next open spot in the bookshelf, such as private int
nextEmpty.

• public Bookshelf getBooksByAuthor(String author) – return a new Bookshelf object


containing only the books which were written by a given author. If no books were written
by the given author, the returned Bookshelf should be empty.
• public String toString() – Build a string of all of the Book objects in the array. Separate
each Book with a single newline character.

Milestone 1:
Write up a few tests for your methods and show them to your TA (remember, your
work must be done in an IDE such as IntelliJ or Eclipse).

2 Sorting Our Bookshelf Class


Our bookshelf might be functional, but it may as well not even be called a shelf. There’s no
order to it! This could be a pile of books, and no one could tell the difference. Therefore, we
need to sort it. Handily enough, our Book class comes with a special compareTo method. I’m
sure you’ve probably used operators like < or > all the time. These operators, unfortunately,
can’t be used on objects in Java. This is where methods such as compareTo come into play.
compareTo is very similar to the equals method, except it returns an int based on how the two
objects compare. If object a is less than object b, then [Link](b) should return a negative
number. If not, it should return a positive number or zero.

The two compareTo methods already exist in the Book class. It is recommended that you take a
look at them to see how they are used. For this section of the lab, implement a
public void sort (char sortBy)
method in your Bookshelf class, which reorders the objects in the Bookshelf so that they
correspond to the ascending order of the compareTo method. The parameter char sortBy
corresponds to the char compareBy parameter of the second compareTo() method in the Book
class. Feel free to use any reasonable sorting algorithm you have learned to accomplish this
task (including any that have been posted on Canvas).

2
CSCI 2081 LAB 5

Caution: Remember to make sure you aren’t trying to sort any null elements at the end
of your array! The member variable nextEmpty may be of some help here.

Milestone 2:
Write at least two tests for your sort method, and show them to your TA (remember,
your work must be done in an IDE – but the tests can be in a separate class that uses your
sort method).

3 File I/O
Now we have a working Bookshelf class, and that’s fantastic. However, hardcoding every book’s
title, author, and rating and then recompiling every time we want to make a change is
incredibly time-consuming. This is where file I/O comes in handy. Instead of hardcoding every
book’s information into your BookShelf, we can simply create a method that reads in that
information from a file.

Your task for this section is to create a BookshelfReader class and write two methods for it:

• public static Bookshelf readBooksFromFile(String fileName)


• public static void writeShelfToFile(Bookshelf b, String fileName)

The class does not need a constructor or any other methods. The first method will accept a file
name(such as the file provided with the lab: [Link]) and create a new Bookshelf object
containing all the books in the file. To write this method, you will need to import File and
Scanner. An example setup for file input is listed below. Once you have a Scanner for the file,
you can use it just as you would any other Scanner. You can assume all input files will be .csv
files. You may also assume that the number of books in any file is never greater than 20 and that
commas are never used as a part of a title or author name. If you don’t know where to begin with
this method, you may want to take a look at the lab from week 4 again.

The second method accepts a reference to a Bookshelf object and a file name (such as
[Link]) and writes all the information about the books stored in the Bookshelf to the file.
You will need to import PrintWriter for this task. A PrintWriterobject can be called with print
or println methods, much like you would call them on [Link].

Example of using Scanner and PrintWriter on a File on the next page:

3
CSCI 2081 LAB 5

// assume our filename is stored in the string fileName


Scanner s = null; // declare s outside try-catch block

try {
s = new Scanner(new File(fileName));
} catch (Exception e) { // returns false if fails to find fileName
return false;
}
// Now use s in the same way we used Scanners previously for user input
// and then close the scanner!

// To write to an arbitrary text file, do the following:


// assume our filename is stored in the string fileName
PrintWriter p = null; // declare p outside try-catch block
try {
p = new PrintWriter(new File(fileName));
} catch (Exception e) {
return false;
}
Here is a link to an example of how to use a PrintWriter to write to a file:
[Link]

Milestone 3:
Write a main method which reads in a Bookshelf from [Link], sorts the bookshelf
by rating, then writes it to [Link] (remember, your work must be done in an IDE).

4 2D Arrays
In this section of the lab, we will discuss 2D arrays, which are used in a wide variety of
applications in software, such as data structures to store and manipulate information in 2D
video games, and mathematical operations (matrix operations such as multiplication and many
others). A 2D array is just an array of arrays. One way to declare a 2D array and initialize a 2D
array can be seen in the following example: int[][] tdArr = new int[5][7];
Here, tdArr is a two-dimensional array of integers, with 5 rows and 7 columns. Accessing an
index of tdArr like tdArr[i] allows us to access the ith row of tdArr (this value would have type
int[]). Doing something like tdArr[i][j] accesses the integer at the ith row and jth column of tdArr.
One important thing to keep in mind is that not all 2D arrays have equally-sized rows; however,
for this problem, you can assume that the 2D arrays have equally-sized rows (that is, all rows

4
CSCI 2081 LAB 5

contain the same number of columns). Your goal is to write a Matrix class with the following
methods and class variables:

• private int nrows; //the number of rows of the matrix


• private int ncols; //the number of columns of the matrix
• private int[][] matrix; //2D array which acts as the actual matrix for the class
• public Matrix(int nrows, int ncols)
• public Matrix(int[][] arr)
• public Matrix transpose()

The first constructor takes in two arguments representing the number of rows and columns of
the matrix. It initializes the matrix based on these values (Java will automatically set every
value in the 2D array of numbers of any kind - integers, longs, floats, doubles, etc., to be zero).

The second constructor takes in a 2D array and creates a matrix (2D array) consisting of nrows
and ncols. It also sets the class variables nrows and ncols to the size of the input array (the
values passed in as parameters and assigned to the parameters nrows and ncols when the
constructor is called).

The transpose() method essentially returns a mirror image of your Matrix. The ith row of your
matrix becomes the ith column of the return Matrix. This method should essentially work as
follows: create a new Matrix that has nrows equal to the number of rows of your matrix and
ncols equal to the number of columns of your matrix. Then iterate through all the rows and
columns of your matrix, setting each entry in the new matrix to be the same entry in your
matrix, but with the order of the indices flipped. For example: [Link][j][i] =
[Link][i][j]

A design of the transpose algorithm is:

procedure TRANSPOSE():
for i ← 0 to nrows -1 do
for j ← 0 to ncols -1 do
newMatrix[j][i] ← Matrix[i][j]
return B

5
CSCI 2081 LAB 5

Milestone 4:
Write a main method where you create a Matrix, print out its contents, and then print
out the contents of its transpose by calling the transpose() method (a toString() method in
your Matrix class may be helpful when printing the contents of a matrix).

5 Challenge

Note: This section and milestone are not required. You are encouraged to work on it if interested
and time permits.

Now that we have a way to add books to our shelves, we should provide a way remove a book
from the bookshelves. Implement the following method in Bookshelf:

public Book remove(String author, String title)

This function should search the array, looking for the book with a certain author and title. If the
book isn’t found, return null. If it is, remove it from the books array and return the Book object.
Additionally, the remove method should shift all books to fill the gap left by the empty book. Do
what is necessary so that the add method still runs in O(1) time. Be sure to rerun all of your
previous tests to make sure you didn’t break any functionality.

Challenge Milestone:
Write three tests that check the following:
Does the returned book match the one that was requested?
After calling remove, does the book no longer exist in the array?
After removing a few books, does my add method still work?

You might also like