Question

You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an...

You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an array of instances of the class Book. The class Book is loaded in our Canvas files: Book.javaPreview the document

  • The user will enter a number n (n must be > 0, trap the user until they input a valid value for n), Your program will declare and create an array of size n of instances of the class Book.
  • The user will be asked to enter the information for each instance that is to be created. The following exceptions will be thrown if the user enters information that is not appropriate to the request:
  • InputMismatchException: Thrown if the user enters a non-matching type. Trap the user until they enter a valid value.
  • PagesException: Thrown if the user enters a number <=0 for the number of pages. Trap the user until they enter a valid value.
  • CostException: Thrown if the user enters a number < 0 for the cost of the book. Trap the user until they enter a valid value.
  • CategoryException: Thrown if the user enters a value other than "Fiction", “Non-Fiction", "Reference", or “Text" for the category of the book. Trap the user until they enter a valid value.
  • You are to create the classes PageException,.java, CostException.java and CategoryException.java (children of the class Exception). The string stored in the instance variable message of the respective exception classes should indicate which exception was thrown. InputMismatchException is a class of the Java language, see the Java API for more information.
  • Upon entrance of acceptable information the gathered information will be the arguments passed to the non-default constructor, of the Book class, the instance created will be saved in the array of instances of the class Book.

Name your program BookExceptionsDemo_yourInitials..java, where yourInitials represents your initials and send all programs developed for this assignment (including Book.java). It would be helpful if you could put those files in a zip file (name that zip file BookExceptions_yourInitials.zip, where yourInitials represents your initials).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Summary :

Following files are pasted below and Demo output is shown towards end as 2 exhibits.

BookExceptionDemo.java

Book.java

PagesException.java

CostException.java

CategoryException.java

InputMismatchException.java

############################### BookExceptionDemo.java ####################

import java.io.RandomAccessFile;
import java.util.Scanner;
import java.util.ListIterator;
import java.util.*;
import java.io.*;
import lib.PagesException;
import lib.InputMismatchException;
import lib.CategoryException;
import lib.CostException;

import lib.Book;

public class BookExceptionsDemo {
   Scanner in ;
   int num_books ;
   Book[] book_list ;
   boolean flag ;
  
   public BookExceptionsDemo() {
        in = new Scanner(System.in);
       num_books = -1;
       this.flag = false ;
   }
  
   public boolean getFlag() {
       return this.flag ;
   }
  
   public void resetFlag() {
       this.flag = false ;
   }
  
   public void setFlag() {
       this.flag = true ;
   }
   // Read num of books
   public void readNumBooks() throws InputMismatchException {

       System.out.println("Enter number of Books : ");
       int input = in.nextInt(); in.nextLine();
       if ( input > 0 ) {
           this.num_books = input ;
       } else {
           throw new InputMismatchException();
       }
  
   }
   // Read Pages input
   public int readPages() throws PagesException {

       System.out.println("Enter Pages : ");
       int input = in.nextInt();in.nextLine();
       if ( input > 0 ) {
           return input;
       } else {
           throw new PagesException();
       }
  
   }
  
   // Read Cost Input
   public int readCost() throws CostException {

       System.out.println("Enter Cost : ");
       int input = in.nextInt();in.nextLine();
       if ( input >= 0 ) {
           return input;
       } else {
           throw new CostException();
       }
  
   }
  
   // Read Category Input
   public String readCategory() throws CategoryException {

       System.out.println("Enter Category of Books : ");
       String input = in.nextLine();
       if ( ("Fiction".equals(input) ) || ("Non-Fiction".equals(input)) || ("Reference".equals(input) ) || ("Text".equals(input))) {
           return input ;
       } else {
           throw new CategoryException();
       }
  
   }
  
  
    public static void main(String[] args) {
       // Flag to loop while invalid inputs
       boolean input_received = false ;
       // Values to store temp Book parameters
       int cost =0 , pages =0 ;
       String category = " "       ;
      
       BookExceptionsDemo be = new BookExceptionsDemo() ;
      
           // Read Num of Books till valid
       while( !input_received) {
           try {
               be.readNumBooks();
               input_received = true ;
           } catch (InputMismatchException e ) {
                   System.out.println(" Invalid Number of books : " );
                   e.getMesg();
                  
           }
          
       }
       // Create Num_Books array of Book
       be.book_list = new Book[be.num_books];
      
       // Loop thru num_books reading pages cost and category
       for ( int i = 0 ; i < be.num_books ; i ++ ) {
           input_received = false ;
           while ( ! input_received ) {
               try {
                   pages = be.readPages();
                   input_received = true;
               } catch ( Exception e ) {
                   System.out.println(" Invalid Pages " );
                              
               }
           }

           input_received = false ;
           while ( ! input_received ) {
               try {
                   cost = be.readCost();
                   input_received = true;
               } catch ( Exception e ) {
                   System.out.println(" Invalid Cost " );
                              
               }
           }          
          
          
          
           input_received = false ;
           while ( ! input_received ) {
               try {
                   category = be.readCategory();
                   input_received = true;
               } catch ( Exception e ) {
                   System.out.println(" Invalid Category " );
                              
               }
           }

           // Create Book and insert into Array .
           be.book_list[i] = new Book(pages,cost , category);
          
       }

       // Display ALl the Books .
       for (int j = 0 ; j < be.num_books ; j++ ) {
          
           be.book_list[j].display();
       }

   }


}

############################### End BookExceptionDemo.java ####################

############################### Book.java ####################

package lib;
public class Book {

   private int pages ;
   private int cost ;
   private String category ;


   public Book() {
       this.pages = 0 ;
       this.cost = 0;
       this.category = " " ;
   }


   public Book( int ppages , int pcost , String pcategory ) {
       this.pages = ppages ;
       this.cost = pcost;
       this.category = pcategory ;
   }


   public void display() {
       System.out.println( " Category : " + category + " Pages : " + pages + " Cost : " + cost );
   }

}  

############################### End Book.java ####################

############################### PagesException.java ####################

package lib;

public class PagesException extends Exception {


   public PagesException() {
        super("Pages value Invalid \n");
   }  

   public String getMesg() {
       return "Pages value Invalid";
   }

}

############################### End PagesException.java ####################

############################### CostException.java ####################

package lib;

public class CostException extends Exception {


   public CostException() {
        super("Cost value Invalid \n");
   }  

   public String getMesg() {
       return "Cost value Invalid";
   }

}

############################### End CostException.java ####################

############################### CategoryException.java ####################

package lib;

public class CategoryException extends Exception {


   public CategoryException() {
        super("Category value Invalid \n");
   }  

   public String getMesg() {
       return "Category value Invalid";
   }

}

############################### End CategoryException.java ####################

############################### InputMismatchException.java ####################

package lib;

public class InputMismatchException extends Exception {


   public InputMismatchException() {
        super("Input Number Invalid \n");
   }  

   public String getMesg() {
       return "Input Number Invalid";
   }

}

############################### End InputMismatchException.java ####################

############################### Output0 ####################

usr@DESKTOP-VUMS 26N:/mnt/i/PRJ/Code/jv/lib$ java Book Exceptions Demo Enter number of Books : -1 Invalid Number of books : E

############################### End Output0####################

############################### Output1 ####################

Invalid Pages Enter Pages : Enter Cost : Invalid Cost Enter Cost : Enter Category of Books : abc Invalid Category Enter Categ

############################### End Output1####################

Add a comment
Know the answer?
Add Answer to:
You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Be sure to include a message to the user explaining the purpose of the program before...

    Be sure to include a message to the user explaining the purpose of the program before any other printing to the screen. Be sure to include information about which document codes are valid. Within the main method, please complete the following tasks in java program: Create a loop that allows the user to continue to enter two-character document designations until a sentinel value is entered (ex. “XX”). If the user enters a valid document code, please echo that value back...

  • For practice using exceptions, this exercise will use a try/catch block to validate integer input from...

    For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner...

  • Write a Java program that will create an array of Strings with 25 elements. Input Strings...

    Write a Java program that will create an array of Strings with 25 elements. Input Strings from the user and store them in the array until either the user enters “quit” or the array is full. HINT: the sentinel value is “quit” all lowercase. “Quit” or “QUIT” should not stop the loop. HINT: you have to use the equals method (not ==) when you are comparing two Strings. After the input is complete, print the Strings that the user entered...

  • College of Winston and Charlotte This program will calculate the amount for a semester bill at...

    College of Winston and Charlotte This program will calculate the amount for a semester bill at The College of Winston and Charlotte. Part 1: Create a class Course.java: The class has non-static instance variables: private String department private int courseNumber private int courseCredits private double courseCost The class must have a default constructor which will set values as follows: department = “unknown” courseNumber = 0 courseCost = 0 courseCredits = 0 The class must have a non-default constructor which will...

  • Java Question, I need a program that asks a user to input a string && then...

    Java Question, I need a program that asks a user to input a string && then asks the user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value...

  • java punu ile 20 maze from chapter 12. 2. StringToolong.java → Write a program that creates...

    java punu ile 20 maze from chapter 12. 2. StringToolong.java → Write a program that creates an exception class called StringTooLongException, designed to be thrown when a string is discovered that too many characters in it. In the main driver of the program, read strings from th user until the user enters "DONE". If a string is entered that has too many chara (say 20), throw the exception. Allow the thrown exception to terminate the program.

  • Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program...

    Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program named GetIDAndAge that continually prompts the user for an ID number and an age until a terminal 0 is entered for both. If the ID and age are both valid, display the message ID and Age OK. Throw a DataEntryException if the ID is not in the range of valid ID numbers (0 through 999), or if the age is not in the range...

  • This is a Java beginner class. Write the following exercise to check the user inputs to...

    This is a Java beginner class. Write the following exercise to check the user inputs to be: Valid input and positive with using try-catch (and/or throw Exception ) ************************************************************************** Write a program to prompt the user for hours and rate per hour to compute gross pay. Calculate your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. Your code should have at least the following methods to calculate the pay. (VOID and...

  • You are to create a class Appointment.java that will have the following: 5 Instance variables: private...

    You are to create a class Appointment.java that will have the following: 5 Instance variables: private String month private int day private int year private int hour private int minute 1 default constructor public Appointment() 1 non-default constructor that accepts arguments for all instance variables, your constructor must call the setter methods below to set the values of the instance variables public Appointment(String monthPassed, int dayPassed, int yearPassed, int hourPassed, int minutePassed) 5 setter methods (one for each instance variable)...

  • FOR JAVA: Summary: Create a program that stores info on textbooks. The solution should be named...

    FOR JAVA: Summary: Create a program that stores info on textbooks. The solution should be named TextBookSort.java. Include these steps: Create a class titled TextBook that contains fields for the author, title, page count, ISBN, and price. This TextBook class will also provide setter and getter methods for all fields. Save this class in a file titled TextBook.java. Create a class titled TextBookSort with an array that holds 5 instances of the TextBook class, filled without prompting the user for...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT