Question

In: Computer Science

Question 1 Download the files Book.java and BookInfo.txt from Content->Chapter 12 Quiz Files. Create a BookDriver.java...

Question 1

Download the files Book.java and BookInfo.txt from Content->Chapter 12 Quiz Files. Create a BookDriver.java class with a main method. In the main method, create an ArrayList of Book objects, read in the information from BookInfo.txt and create Book objects to populate the ArrayList. After all data from the file is read in and the Book objects added to the ArrayList- print the contents of the ArrayList. Paste your BookDriver.java text (CtrlC to copy, CtrlV to paste) into the open space before. You should not change Book.java or BookInfo.txt.  

Given info below :

/**
*
* Book
*
* @author bbrown25
*
* A class to represent information about a Book
*
**/
public class Book
{
   private String title;
   private String author;
  
  
   /**
   * No arg constructor
   */
   public Book()
   {
       title = "not set";
       author = "not set";
   }
  
   /**
   * @param title
   * @param author
   */
   public Book(String title, String author)
   {
       super();
       setTitle( title);
       setAuthor(author);
   }

   /**
   * @return the title
   */
   public String getTitle()
   {
       return title;
   }

   /**
   * @param title the title to set
   */
   public void setTitle(String title)
   {
       if (title.length() > 0)
       {
           this.title = title;
       }
       else
       {
           this.title = "not set";
       }
   }

   /**
   * @return the author
   */
   public String getAuthor()
   {
       return author;
   }

   /**
   * @param author the author to set
   */
   public void setAuthor(String author)
   {
       if (author.length() > 0)
       {
           this.author = author;
  
       }
       else
       {
           this.author = "not set";
       }
   }

   @Override
   public String toString()
   {
       return "Book [title=" + title + ", author=" + author + "]";
   }


  
}

BookInfo.txt

War and Peace
Leo Tolstoy
Pride and Prejudice
Jane Austen
Gone With the Wind
Margaret Mitchell

Solutions

Expert Solution

Code Solution:

//imports required in the program
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

//BookDriver class
public class BookDriver {
    public static void main(String[] args) {
        // instantiating an ArrayList of type Book
        ArrayList<Book> books = new ArrayList<>();
        //try catch block is used to handle any I/O errors
        try {
            //Setting up the FileReader and BufferedReader to read the BookInfo.txt file
            FileReader fileReader = new FileReader(new File("BookInfo.txt"));
            BufferedReader bufferedreader = new BufferedReader(fileReader);

            //Variables to store the current line read from file and the book name
            String strLine,currentBook = "";

            //a counter variable to note the index of current line being read
            int i = 1;

            //while loop to read the line
            while ((strLine = bufferedreader.readLine()) != null) {
                //analysing the BookInfo.txt, we can see that 1st line has book name
                //next has the author and this way it goes on.
                //So, our logic says that if the line number is odd, store the value of book title.
                if(i%2!=0)
                currentBook = strLine;
                //else if the current line has author name, add the book to the arraylsit using constructor.
                //currentBook holds the value of book title and strLine(current line being read) has the author name
                else
                books.add(new Book(currentBook,strLine));
                //increment i everytime a line is read
                i+=1;
            }
            //closing the input stream
            fileReader.close();
        }
        //catch block
        catch (IOException e) {
            e.printStackTrace();
        }
        //printing the contents of arraylist
        System.out.println(books);
    }
}

Screenshot for reference:

Output:

We read the file using bufferedReader provided by Java. We formulate the logic using the fact that every odd number line contains Book title and even number line contains the author name. Whenever the line is odd, we store the book title in currentBook variable. When it is even, we add the book in the ArrayList setting the title as currentBook and the author as the current read line stored in strLine variable.


Related Solutions

Question 2: Download the Excel data file "Arlington_Homes" from the folder "Data" under "Chapter 12." a)...
Question 2: Download the Excel data file "Arlington_Homes" from the folder "Data" under "Chapter 12." a) read the data file in R. b) using R, answer question 65 (a, b, and c) on page 411 of your book. Run the regression, show the estimates and test. Write what you are testing using a comment in the R program. Question #65. link for page 411 #65 https://imgur.com/s0SgxP3 please show every step for R frmulas Price Sqft Beds Baths Col 840000 2768...
Chapter Quiz: BA118ch08 Started: Apr 22 at 6:52pm Quiz Instructions Flag this Question Question 12 pts...
Chapter Quiz: BA118ch08 Started: Apr 22 at 6:52pm Quiz Instructions Flag this Question Question 12 pts 1. One of the major objectives of financial plans is to build traffic. True False 2. Which of the following is a type of financial statement fraud? All of these answers are correct Taking advantage of the accounting cutoff period to boost sales Concealing paperwork related to expenses Overstating inventory value Not disclosing all changes in accounting procedures 3. The income statement includes which...
× course.content.assessment.attempt.menu Test Finance Proficiency Quiz 1 Finance Proficiency Quiz 1 Test Content Question 1 10...
× course.content.assessment.attempt.menu Test Finance Proficiency Quiz 1 Finance Proficiency Quiz 1 Test Content Question 1 10 Points Net sales are $10,000,000, beginning total assets are $2,000,000, and the asset turnover is 4.0 times. What is the ending total asset balance? $2,000,000 $2,500,000 $3,000,000 $4,000,000 Question 2 10 Points Which one of the following is a component of Liquidity analysis? Asset Turnover Current Ratio Return on Assets Debt to Total Assets Question 3 10 Points Darius, Inc. has the following income...
Go to the Files section and download the AFE_Test file from the Datasets folder. We are...
Go to the Files section and download the AFE_Test file from the Datasets folder. We are interested in a one­tail test described in the following fashion: Ho: u < or = to 200 CFM; H1: u > 200 CFM. At 5% significance level, we can reject the null hypothesis given the sample information in AFE_Test1. we can reject the null hypothesis given the sample information in AFE_Test2. we cannot reject the null hypothesis. we can reject the null hypothesis given...
ACC 202 QUIZ 1 Chapter 1,2,3
1) Direct costs: A) are incurred to benefit a particular accounting period. B) are incurred due to a specific decision. C) can be easily traced to a particular cost object. D) are the variable costs of producing a product. 2) Which of the following is NOT a period cost? A) Depreciation of factory maintenance equipment. B) Salary of a clerk who handles customer billing. C) Insurance on a company showroom where customers can view new prod D) Cost of a seminar concerning tax...
The question is from the textbook Inequality, Discrimination, Poverty, and Mobility Question 2 from chapter 12:...
The question is from the textbook Inequality, Discrimination, Poverty, and Mobility Question 2 from chapter 12: "How responsible are people for their own poverty? What responsibility does the government have in the alleviation of poverty?"
Please, Use C++ The files in question are Square.cpp, Square.h, SquareContainer.cpp, SquareContainer.h and ClassTest.cpp. Please download,...
Please, Use C++ The files in question are Square.cpp, Square.h, SquareContainer.cpp, SquareContainer.h and ClassTest.cpp. Please download, compile and run these files, and convince yourself that you understand what they do. Question Is there a problem with the fact that SquareContainer.h defines two classes? Coding (finish in 60min) - just try to finish as many as you can Add an overloaded assignment operator to the Square class. Add a "<" operator for Square objects, which returns "true" when a Square object's...
This assignment uses a combination of classes and arrays. Instructions: 1) download the 3 program files...
This assignment uses a combination of classes and arrays. Instructions: 1) download the 3 program files into a new C++ project.    NOTE: if your IDE does not allow you to create projects - or you are not sure how to do it - then you may combine the two cpp files into a single file. 2) Complete the program by adding code the the class methods. You may want to study the existing code first to get a feel...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter)...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter) for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of the class-the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For...
Chapter 15 Discussion Group Question                                Gender differences in dream content
Chapter 15 Discussion Group Question                                Gender differences in dream content are well documented (see Winget & Kramer, 1979). Suppose a researcher studies aggression content in the dreams of men and women. Each participant reports his or her most recent dreams. Then each dream is judged by a panel of experts to have low, medium, or high aggression content. The observed frequencies are shown in the following matrix:    Aggression Content Low medium high female 18 4 2 male 4...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT