Language: Java Part I The Book class has the following attributes: an ISBN (long
ID: 3867246 • Letter: L
Question
Language: Java
Part I
The Book class has the following attributes: an ISBN (long type), a title (String type), an issue year (int type), an author(s) name (String type), a price (double type) and a number of pages (int type). It is assumed that both the title and the author(s) name are recorded as a continuous string with “_” to separate the different words if any (i.e. a title can be Java_Applications_for_Engineers, and author name can be Mike_Westman_and_Jack_Bartlett).
The file Initial_Book_Info.txt, which one of its versions is provided with this assignment, has the information of various books that a book store carries. However, this file is always created by the owner of the book store, who is not so careful, so errors in the ISBN numbers are expected to exist in this file. Specificaly, due to a cut-and-paste practice by the owner, some ISBN numbers of some books are usually re-recorded later in the file as the ISBN number of other following books in the file. Consequently, an ISBN can either appears once in the file, which is the correct case, or appears multiple times, in which case the second, and following, appearances are in error.
You must notice that the file Initial_Book_Info.txt changes regularly, and it may have many records, or no records at all, depending on the current inventory of the store. The file provided with this assignment is only one of possible versions of the file, and must not be considered as the general case when writing your code.
For this part, you are required to:
Write the implementation of the Book class according to the above given specification.
Write the implementation of an exception class called DuplicateISBNException, which extends the Exception class. Should a duplicate ISBN number is detected at any point, an object from this class will be thrown. More details will follow below.
Write the implementation of a public class, called BookInventory1, which will utilize the Book class and the Initial_Book_Info.txt, as explained below. The class has a static array of books, called bkArr[], and few methods. Beside the main() method, the class must have the following methods:
• A method called fixInventory(), which accepts two parameters, an input file stream name and an output file stream name. The first parameter is the stream related to the Initial_Book_Info.txt. The second parameter is related to an output file name, which will be entered by the user prior to calling this method (at the main() method). This output file will eventually store a correct version of the inventory. More information on this will follow below.
• A method called displayFileContents(), which accepts an input file stream name, then displays the contents of this file to the standard output (the screen).
• You can add any other methods to this class if you wish to.
Here are the details of how your program must behave:
• In the main() method, your program must prompt the user to enter the name of the output file that will be created to hold the modified/correct inventory. This output file is theoretically a copy of the Initial_Book_Info.txt, but with all the duplicate ISBN numbers corrected.
· If the entered name by the user matches the name of an existing file, then the program must reject that name indicating to the user that a file with that name already exists, display the size of this existing file (in bytes) to the user, then prompt the user to enter a new name. This process would repeat indefinitely, until the user finally enters a name for a non- existing file. See Figure1 for illustration.
Once the user finally enters a correct name for the output file, the program will attempt to establish an input and output streams for the Initial_Book_Info.txt and that output file accordingly. This process may surely throw specific exceptions, and your program must handle all these exceptions properly.
The fixInventory() method (see details below) will utilize the BkArr[] array as follows: All book objects recorded in the Initial_Book_Info.txt file must first be copied into that array. All detections and corrections of ISBN numbers will be conducted on that array. Once the array has finally all correct information, the objects will be recorded to the output file. However since it always unknown at the time the program starts how many records are in the Initial_Book_Info.txt file, you must first find this information. You may, and should, add a private helping method to the BookInventory1 class to do so. Once the number of records is know, the array must be set to that size.
If the number of records in the Initial_Book_Info.txt was detected to be zero or one; the case when the file is empty or has only one record, then the program must display a message indicating that, performs any needed operations (such as closing files), then exits since there is nothing to be fixed.
If the Initial_Book_Info.txt has more than one record, then finally the fixInventory() method will be called to create a the new output file with the correct information. The exact details of this method are as follows:
o The method will accept two stream names for the input and output files,
o The method must read each book record from the input file and creates a book object in the array bkArr[] based on that record,
o Once the entire input file is read into the array (notice that the array has real book objects, and not just information), the method starts to trace that array from start to end looking for any ISBN duplicates,
o If an ISBN duplicate is detected, then the method displays a message to the user indicating that, and prompt the user to enter a new ISBN number,
o You should notice that this new number must not be a duplicate of any other existing record, and your program must guarantee that. Should the user enters an ISBN number that is still a duplicate, the program must throw a DuplicateISBNException, which must be catched to display a message indicating that, then user must be prompted again to enter a new ISBN. Further bad entries will result in the same action; that is throwing of the DuplicateISBNException object, catching it to display the message, and the user is prompted again. Effectively, this process will repeat indefinitely until the user enters a correct ISBN number. Again, you may, and should, create a private helping method to find if a duplicate exists in the array.
o Finally, once all the duplicate ISBN numbers are removed, the new information of the objects in the bkArr[] must be copied to the output file. This output file has now the correct information.
• Upon the return of the fixInventory() call in the main() method, the program must use the displayFileContents() method to display the information of both the Initial_Book_Info.txt file, as well as the created output file. See Figure 3 for illustration. Hint: You must carefully keep track of the opening and closing of these files.
Part II
For this second part, you will still use the same Book class from Part I (some little modifications may be needed, and you should find that out). Other code segments from Part I can still be used when appropriate.
Implement a public class called BookInventory2, which will utilize the Book class and the file called Sorted_Book_Info.txt. This file includes information about books inventory in a book store. The records in this file are sorted by ISBN, and the information in this file is assumed to always be correct.
The class has a static array of books, called bkArr[], and few methods. Beside the main() method, the class must have the following methods:
A method called addRecords(), which accept one parameter: an output file stream name; further details of this method are given below.
A method called displayFileContents(), which accepts an input file stream name, then displays the contents of this file to the standard output (the screen). This method however must use the BufferedReader class to read the file.
A method called binaryBookSearch(), which accepts four parameters: any array of books, a start index, an end index, and an ISBN number. The method then uses binary search to search the array segment (from start index to end index) for that ISBN. The method must also keep track and display how many iterations it needed to perform the search.
A method called sequentialBookSearch(), which accepts four parameters: any array of books, a start index, an end index, and an ISBN number. The method would then search the array, using sequential search, for that ISBN. You must analysis the performance aspect of your solution. Hence, the method must also display how many iterations it needed to perform the search.
You can add any other methods to that class if you wish to.
Here are the details of how your program must behave:
In the main() method, your program must open the Sorted_Book_Info.txt file to append few records to it.
Call the addRecords() method to add few records to the file. The information of each of the new records must be entered by the user. The user can add as many records as he/she wishes (you must surely allow the user to have a stopping condition limiting the numbers of records that can be added). To simplify your task, you can assume that the user will always keep the file sorted; that is, no new record will have an ISBN# that is smaller than any of the previous records in the file., in a nother way a reference of the last record is kept to accept or reject the record you want to add.
Call the displayFileContents() method to show the contents of the file after modifications.
Now, the array bkArr[] is going to be used in a similar fashion to Part I. So, you need to find out what is the current number of records in the Sorted_Book_Info.txt file, and set the size of the array to that number. You may, and should, have a private helping method to do so.
After setting the array size properly, the program must read the contents of the file to the array objects. You can use a separate method to do so.
Once the array has the objects information from the file, prompt the user to enter and ISBN number then use binaryBookSearch() to search for that ISBN.
Repeat the same search using sequentialBookSearch().
- As an important exercise, you should run your code for different searches (i.e. attempt to find best and worst cases) of the two searches.
Finally, store all the objects from the bkArr[] into a binary file called Books.dat. You can have a separate method to do so. If writing to the binary file requires any specific modifications to your code, you must apply these modifications.
- As always, you must handle all exceptions as needed and you must keep track of the opening and closing of your files.
Explanation / Answer
PartOne
------------------------
Book.java
-------------------------
public class Book {
private long isbn;
private String title;
private String authorName;
private int issueYear;
private int numOfPages;
private double price;
public Book(){
isbn = 0;
title = null;
authorName = null;
issueYear = 0;
numOfPages = 0;
price = 0;
}
public Book(long isbn, String title, int issueYear, String authorName, double price, int numOfPages){
this.isbn = isbn;
this.title =title;
this.authorName = authorName;
this.issueYear = issueYear;
this.numOfPages = numOfPages;
this.price = price;
}
public long getIsbn(){
return this.isbn;
}
public void setIsbn(long isbn){
this.isbn = isbn;
}
public String toString(){
return (this.isbn + " " + this.title +" by " + this.authorName +", "
+ this.issueYear + ", " + " $"+ this.price + ", " + this.numOfPages + " pages");
}
}
-----------------------------------------------------------------------
BookInventory1.java
---------------------------------------
import java.util.Locale;
import java.io.*;
import java.util.Scanner;
import java.util.InputMismatchException;
public class BookInventory1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String newFileName = null;
try{
System.out.println("Please enter the name for the updated inventory: ");
String newFile = keyboard.next();
File fixedBookInvFile = new File(newFile);
while (!fixedBookInvFile.createNewFile()){
System.out.println("Error! There is an existing file with the name "+ fixedBookInvFile.getName()+".");
System.out.println("That file has a size of "+fixedBookInvFile.length()+" bytes.");
System.out.println("Please enter another name: ");
newFile = keyboard.next();
fixedBookInvFile = new File(newFile);
}
newFileName = fixedBookInvFile.getName();
fixInventory("Initial_Book_Info.txt", newFileName);
}
catch (IOException e){
System.out.println("Exception found!");
System.out.println(e.toString());
}
System.out.println("Here are the contents of the file Initial_Book_Info.txt AFTER copying operation:");
System.out.println("==================================== ");
displayFileContents("Initial_Book_Info.txt");
System.out.println(" Here are the contents of the file "+newFileName+":");
System.out.println("==================================== ");
displayFileContents(newFileName);
}
private static int NumOfLines(String originalFile){
int numOfBooks = 0;
BufferedReader inputStream = null;
try{
System.out.println("Attempting to open file:"+originalFile+" ");
inputStream = new BufferedReader(new FileReader(originalFile));
while(inputStream.readLine() != null){
numOfBooks++;
}
inputStream.close();
System.out.println("Detecting number of records in file: "+originalFile+" ");
}
catch(IOException e){
System.out.println("File not found!");
System.exit(0);
}
if (numOfBooks==0){
System.out.println("There are no books to sort. Thank you, goodbye.");
System.exit(0);
}else if (numOfBooks==1){
System.out.println("There is only "+ numOfBooks +" book to enter. Thank you, goodbye");
System.exit(0);
}
System.out.println("This file contains "+numOfBooks+" books. ");
return numOfBooks;
}
public static void fixInventory(String roughBookInvFile, String fixedBookInvFile){
Book[] BkArr = new Book[NumOfLines("Initial_Book_Info.txt")];
Scanner keyboard = new Scanner(System.in);
Scanner inputStream = null;
PrintWriter outputStream = null;
try{
inputStream = new Scanner(new FileReader("Initial_Book_Info.txt"));
inputStream.useLocale(Locale.US);
for(int i=0;i<BkArr.length; i++){
BkArr[i] = new Book(inputStream.nextLong(),inputStream.next(),inputStream.nextInt(),
inputStream.next(),inputStream.nextDouble(),inputStream.nextInt());
}
}
catch(IOException e){
System.out.println("File not found!");
System.exit(0);
}
sortIsbn(BkArr)
try{
outputStream = new PrintWriter(new FileOutputStream(fixedBookInvFile));
}
catch (IOException e){
System.out.println("File not found!");
System.exit(0);
}
for(int i=0;i<BkArr.length; i++)
outputStream.println(BkArr[i]);
inputStream.close();
outputStream.close();
keyboard.close();
}
private static void sortIsbn(Book[] roughBkArr){
Scanner keyboard = new Scanner(System.in);
boolean uniqueIsbn;
long isSameIsbn = 0;
for(int i=0;i<roughBkArr.length; i++){
for (int j=i+1;j<roughBkArr.length; j++){
if(roughBkArr[i].getIsbn()==roughBkArr[j].getIsbn()){
System.out.println("Duplicate ISBN "+roughBkArr[j].getIsbn()+" detected in record #"+j+".");
System.out.println("Please enter the correct ISBN: ");
boolean done = false;
while(!done){
try{
isSameIsbn=keyboard.nextLong();
done = true;
}
catch(Exception e){
System.out.println("Invalid input! Please enter a valid ISBN");
keyboard.next();
}
}
uniqueIsbn = false;
while(!uniqueIsbn){
try{
for(int k=0;k<roughBkArr.length;k++)
if(isSameIsbn==roughBkArr[k].getIsbn())
throw new DuplicateIsbnException();
uniqueIsbn=true;
}
catch(DuplicateIsbnException e){
System.out.println(e.getMessage());
System.out.println("Please enter another ISBN: ");
isSameIsbn = keyboard.nextLong();
}
}
roughBkArr[j].setIsbn(isSameIsbn);
}
}
}
keyboard.close();
}
public static void displayFileContents(String fileToDisplay){
BufferedReader inputStream = null;
String line;
try{
inputStream = new BufferedReader(new FileReader(fileToDisplay));
line = inputStream.readLine();
while(line != null){
System.out.println(line);
line = inputStream.readLine();
}
inputStream.close();
}
catch (IOException e){
System.out.println("File not found!");
System.exit(0);
}
}
}
--------------------------------------------------------------------------------
BookInventory2.java
--------------------------------------------
import java.io.*;
import java.util.Scanner;
public class BookInventory2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName = "Initial_Book_Info.txt";
addRecords(fileName);
displayFileContents(fileName);
Book[] bkArr = new Book[numofRecords(fileName)];
Scanner arr = null;
try{
arr = new Scanner(new FileInputStream(fileName));
int i = 0;
while(arr.hasNextLine()){
long isbn = arr.nextLong();
String title = arr.next();
int issueYear = arr.nextInt();
String authorName = arr.next();
double price = arr.nextDouble();
int numofPages = arr.nextInt();
bkArr[i] = new Book(isbn, title, issueYear, authorName, price, numofPages);
i++;
}}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
arr.close();
boolean search = true;
do{
Scanner kb = new Scanner(System.in);
System.out.println("Do you wish to search for a book? (yes or no)");
String ans = kb.next();
ans = ans.toUpperCase();
while(!ans.equals("YES") && !ans.equals("Y") && !ans.equals("NO") && !ans.equals("N")){
System.out.println("Invalid Answer! Please enter valid answer! (yes or no)");
ans = kb.next();
ans = ans.toUpperCase();
}
if(ans.equals("YES") || ans.equals("Y")){
System.out.println("Enter the starting index: (between 0-" + bkArr.length + ")");
int start = kb.nextInt();
while(start < 0){
System.out.println("Invalid! Please enter a valid starting index: (between 0-" + bkArr.length + ")");
start = kb.nextInt();
}
System.out.println("Enter the ending index: (between 0-" + bkArr.length + ")");
int end = kb.nextInt();
while(end > bkArr.length - 1){
System.out.println("Invalid! Please enter a valid ending index: (between 0-" + bkArr.length + ")");
end = kb.nextInt();
}
System.out.println("Enter the isbn:");
long isbn = kb.nextLong();
binaryBookSearch(bkArr, start, end, isbn);
sequentialBookSearch(bkArr, start, end, isbn);
}
else{
System.out.println("You have chosen not to search.");
System.out.println();
search = false;
kb.close();
}
}
while(search);
ObjectOutputStream sortedBinary = null;
try{
sortedBinary = new ObjectOutputStream(new FileOutputStream("Books.dat"));
sortedBinary.writeObject(bkArr);
sortedBinary.close();
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
catch(IOException e){
System.out.println("Error! Program will now exit!");
System.exit(0);
}
}
public static void addRecords(String sortedFile){
Scanner kb = new Scanner(System.in);
PrintWriter add = null;
long isbn = 0;
String title = null;
int issueYear = 0;
String authorName = null;
double price = 0;
int numofPages = 0;
String ans = null;
boolean write = true;
int counter = 0;
try{
add = new PrintWriter(new FileOutputStream(sortedFile, true));
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
do{
System.out.println("Do you wish to enter new book record? (yes or no)");
ans = kb.next();
ans = ans.toUpperCase();
while(!ans.equals("YES") && !ans.equals("Y") && !ans.equals("NO") && !ans.equals("N")){
System.out.println("Invalid Answer! Please enter valid answer! (yes or no)");
ans = kb.next();
ans = ans.toUpperCase();
}
if(ans.equals("YES") || ans.equals("Y")){
System.out.println("Please enter the ISBN:");
isbn = kb.nextLong();
System.out.println("Please enter the title (seperate words by "_"):");
title = kb.next();
System.out.println("Please enter the issue year:");
issueYear = kb.nextInt();
System.out.println("Please enter the author's name:(seperate words by "_")");
authorName = kb.next();
System.out.println("Please enter the price:");
price = kb.nextDouble();
System.out.println("Please enter the number of pages:");
numofPages = kb.nextInt();
add.println(isbn + " " + title + " " + issueYear + " " + authorName + " " + price + " " + numofPages);
counter++;
}
else{
System.out.println("You have chosen not to add anymore records.");
System.out.println(counter + " records were added to the file.");
System.out.println();
write = false;
add.close();
kb.close();
}
}
while(write);
}
public static void displayFileContents(String sortedFile){
BufferedReader filereader = null;
try{
filereader = new BufferedReader(new FileReader(sortedFile));
String line = filereader.readLine();
while(line != null){
System.out.println(line);
line = filereader.readLine();
}
filereader.close();
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
catch(IOException e){
System.out.println("Error! Program will now exit!");
System.exit(0);
}
}
public static void binaryBookSearch(Book[] arr, int start, int end, long isbn){
int middle;
int high = arr.length - 1;
int i = 0;
while(end <= high) {
i++;
middle = (start + end) >>> 1;
if (isbn > arr[middle].getIsbn()){
end = middle + 1;
} else if (isbn < arr[middle].getIsbn()){
high = middle - 1;
} else {
// found the element
System.out.println("Using binary search, we found this book: " + arr[middle]);
System.out.println("ISBN found at index: " + i);
return;
}
}
System.out.println(" No book found.");
return;
/*---------------------
* int counter = 0;
int search = (start + end) >>> 1;
System.out.println("Doing a binary search.");
if(arr[search].getIsbn() <= isbn){
for(int i = search; i <= end; i++){
if(arr[i].getIsbn() == isbn){
System.out.println("ISBN found at index: " + i);
counter++;
}
else
counter++;
if(i == end)
System.out.println("Did not find ISBN.");
}
}
else{
for(int i = search - 1; i >= start; i--){
if(arr[i].getIsbn() == isbn){
System.out.println("ISBN found at index: " + i);
counter++;
}
else
counter++;
if(i == start)
System.out.println("Did not find ISBN.");
}
}
System.out.println(counter + " iterations of the search performed.");
System.out.println();
--------------------------
*/
}
public static void sequentialBookSearch(Book[] arr, int start, int end, long isbn){
int counter = 0;
System.out.println("Doing a sequential search.");
for(int i = start; i <= end; i++){
if(arr[i].getIsbn() == isbn){
System.out.println("ISBN found at index: " + i + " Uusing a sequential search, we found this book: " + arr[i]);
counter++;
return;
}
else
counter++;
if(i == end)
System.out.println("Did not find ISBN.");
}
System.out.println(counter + " iterations of the search performed.");
System.out.println();
}
private static int numofRecords(String sortedFile){
int numofRecords = 0;
BufferedReader filereader = null;
try{
filereader = new BufferedReader(new FileReader(sortedFile));
String line = filereader.readLine();
while(line != null)
{
line = filereader.readLine();
numofRecords++;
}
filereader.close();
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
catch(IOException e){
System.out.println("Error! Program will now exit!");
System.exit(0);
}
return numofRecords;
}
}
-------------------------------------------------------------
DuplicateISBNException.java
--------------------------------------
public class DuplicateIsbnException extends Exception {
public DuplicateIsbnException(){
super("Error! Duplicate ISBN Exception Found! The entered ISBN exists for another record.");
}
public DuplicateIsbnException(String error){
super(error);
}
}
---------------------------------------------------------------------------
Part - II
-------------------------------------------------------
Book.java
------------------------------
import java.io.Serializable;
public class Book implements Serializable{
private long isbn;
private String title;
private int issueYear;
private String authorName;
private double price;
private int numofPages;
public Book(){
isbn = 0;
title = null;
issueYear = 0;
authorName = null;
price = 0.0;
numofPages = 0;
}
public Book(long iSBN, String thetitle, int issueyear, String authorname, double theprice, int numofpages){
isbn = iSBN;
title = thetitle;
issueYear = issueyear;
authorName = authorname;
price = theprice;
numofPages = numofpages;
}
public long getISBN(){
return this.isbn;
}
}
-------------------------------------------------------------
BookInventory2.java
---------------------------
import java.io.*;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BookInventory2 {
public static void main(String[] args) {
String fileName = "Initial_Book_Info.txt";
addRecords(fileName);
displayFileContents(fileName);
Book[] bkArr = new Book[numofRecords(fileName)];
Scanner arr = null;
try{
arr = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
for(int i = 0; i < bkArr.length; i++){
bkArr[i] = new Book(arr.nextLong(), arr.next(), arr.nextInt(), arr.next(), arr.nextDouble(), arr.nextInt());
}
arr.close();
boolean search = true;
do{
Scanner kb = new Scanner(System.in);
System.out.println();
System.out.println("Do you wish to search for a book? (yes or no)");
String ans = kb.next();
ans = ans.toUpperCase();
while(!ans.equals("YES") && !ans.equals("Y") && !ans.equals("NO") && !ans.equals("N")){
System.out.println("Invalid Answer! Please enter valid answer! (yes or no)");
ans = kb.next();
ans = ans.toUpperCase();
}
if(ans.equals("YES") || ans.equals("Y")){
int start = 0;
int end = 0;
boolean input = false;
boolean s = false;
boolean e = false;
long isbn = 0;
while(!input){
try{
while(!s){
System.out.println("Enter the starting index: (between 0-" + (bkArr.length-1) + ")");
start = kb.nextInt();
while(start < 0 || start > bkArr.length-1){
System.out.println("Invalid! Please enter a valid starting index: (between 0-" + (bkArr.length-1) + ")");
start = kb.nextInt();
}
s = true;
}
while(!e){
System.out.println("Enter the ending index: (between 0-" + (bkArr.length-1) + ")");
end = kb.nextInt();
while(end < start || end > bkArr.length - 1){
System.out.println("Invalid! Please enter a valid ending index: (between 0-" + (bkArr.length-1) + ")");
end = kb.nextInt();
}
e = true;
}
System.out.println("Enter the isbn:");
isbn = kb.nextLong();
input = true;
binaryBookSearch(bkArr, start, end, isbn);
sequentialBookSearch(bkArr, start, end, isbn);
}
catch(InputMismatchException f){
System.out.println("Invalid!");
kb.nextLine();
}
}
}
else{
System.out.println("You have chosen not to search for a book.");
System.out.println();
search = false;
kb.close();
}
}
while(search);
ObjectOutputStream sortedBinary = null;
try{
System.out.println("Putting all the information in a binary file named Books.");
sortedBinary = new ObjectOutputStream(new FileOutputStream("Books.dat"));
sortedBinary.writeObject(bkArr);
sortedBinary.close();
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
catch(IOException e){
System.out.println("Error! Program will now exit!");
System.exit(0);
}
}
public static void addRecords(String sortedFile){
Scanner kb = new Scanner(System.in);
PrintWriter add = null;
long isbn = 0;
String title = null;
int issueYear = 0;
String authorName = null;
double price = 0.0;
int numofPages = 0;
String ans;
boolean write = true;
int counter = 0;
try{
add = new PrintWriter(new FileOutputStream(sortedFile, true));
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
do{
System.out.println("Do you wish to enter new book record? (yes or no)");
ans = kb.next();
ans = ans.toUpperCase();
while(!ans.equals("YES") && !ans.equals("Y") && !ans.equals("NO") && !ans.equals("N")){
System.out.println("Invalid Answer! Please enter valid answer! (yes or no)");
ans = kb.next();
ans = ans.toUpperCase();
}
if(ans.equals("YES") || ans.equals("Y")){
System.out.println("Please enter the ISBN:");
boolean done = false;
while(!done){
try{
isbn = kb.nextLong();
done = true;
}
catch(InputMismatchException e){
System.out.println(" Please enter a valid ISBN. ");
kb.nextLine();
}
}
System.out.println("Please enter the title:");
done = false;
while(!done){
try{
title = kb.next();
done = true;
}
catch(InputMismatchException e){
System.out.println(" Please enter a valid title. ");
kb.nextLine();
}
}
System.out.println("Please enter the issue year:");
done = false;
while(!done){
try{
issueYear = kb.nextInt();
done = true;
}
catch(InputMismatchException e){
System.out.println(" Please enter a valid issue year. ");
kb.nextLine();
}
}
System.out.println("Please enter the author's name:");
done = false;
while(!done){
try{
authorName = kb.next();
done = true;
}
catch(InputMismatchException e){
System.out.println(" Please enter a valid author's name. ");
kb.nextLine();
}
}
System.out.println("Please enter the price:");
done = false;
while(!done){
try{
price = kb.nextDouble();
done = true;
}
catch(InputMismatchException e){
System.out.println(" Please enter a valid price. ");
kb.nextLine();
}
}
System.out.println("Please enter the number of pages:");
done = false;
while(!done){
try{
numofPages = kb.nextInt();
done = true;
}
catch(InputMismatchException e){
System.out.println(" Please insert a valid number of pages. ");
kb.next();
}
}
add.println(isbn + " " + title + " " + issueYear + " " + authorName + " " + price + " " + numofPages);
counter++;
}
else{
System.out.println("You have chosen not to add anymore records.");
System.out.println(counter + " records were added to the file.");
System.out.println();
write = false;
add.close();
}
}
while(write);
}
public static void displayFileContents(String sortedFile){
BufferedReader filereader;
try{
filereader = new BufferedReader(new FileReader(sortedFile));
String line = filereader.readLine();
while(line != null){
System.out.println(line);
line = filereader.readLine();
}
filereader.close();
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
catch(IOException e){
System.out.println("Error! Program will now exit!");
System.exit(0);
}
}
public static void binaryBookSearch(Book[] arr, int start, int end, long isbn){
int counter = 0;
int search = (start + end)/2;
System.out.println("Doing a binary search.");
if(arr[search].getISBN() <= isbn){
for(int i = search; i <= end; i++){
if(arr[i].getISBN() == isbn){
System.out.println("ISBN found at index: " + i);
counter++;
}
else
counter++;
if(i == end)
System.out.println("Did not find ISBN.");
}
}
else{
for(int i = search - 1; i >= start; i--){
if(arr[i].getISBN() == isbn){
System.out.println("ISBN found at index: " + i);
counter++;
}
else
counter++;
if(i == start)
System.out.println("Did not find ISBN.");
}
}
System.out.println(counter + " iterations of the search performed.");
System.out.println();
}
public static void sequentialBookSearch(Book[] arr, int start, int end, long isbn){
int counter = 0;
System.out.println("Doing a sequential search.");
for(int i = start; i <= end; i++){
if(arr[i].getISBN() == isbn){
System.out.println("ISBN found at index: " + i);
counter++;
}
else
counter++;
if(i == end)
System.out.println("Did not find ISBN.");
}
System.out.println(counter + " iterations of the search performed.");
System.out.println();
}
private static int numofRecords(String sortedFile){
int numofRecords = 0;
Scanner filereader = null;
try{
filereader = new Scanner(new FileInputStream(sortedFile));
while(filereader.hasNextLong() && filereader.hasNext() && filereader.hasNextInt() && filereader.hasNext() && filereader.hasNextDouble() && filereader.hasNextInt()){
numofRecords++;
filereader.nextLine();
}
filereader.close();
}
catch(FileNotFoundException e){
System.out.println("File not Found! Program will now exit!");
System.exit(0);
}
return numofRecords;
}
}
-------------------------------------------------------------
Initial_Book_Info.txt
----------------------------------
765867999 Java_Applications_for_Programmers 2010 David_Wilson_and_Jack_Westman 173.25 672
465979798 From_Java_to_C++ 2008 Linda_Jackson 118.73 439
760098908 Microsoft_VC++ 2006 Garry_Wesley 165.20 416
529086890 Software_Engineering 2005 Alain_Macmillan 219.99 651
765867999 Visual_Basic 2004 Mary_Rosen 108.33 388
529086890 Database_Systems 2007 Peter_Jones_and_Jack_Lewis 157.87 862
800003243 VLSI 2008 Martha_Niclson 117.29 360
200900210 C_# 2007 D._Smith 109.99 387
200900210 Cellular_Communications 2010 Jones_Tomson 127.87 162
542087665 Pattern_Recognition 1998 Sam_Davis 212.59 328
900876512 Programming_Methodologies 2009 Steve_A._Richmond 182.95 590
900876512 OO_Programming 2008 Frank_Raymond 182.25 439
900876512 Design_Pattern 2002 Jay_Franklin 122.15 217
900876512 Networking_and_Data_Communications 2010 Pete_Jonson 229.25 724
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.