Question

In: Computer Science

Part A: Create a project with a Program class and write the following two methods (headers...

Part A: Create a project with a Program class and write the following two methods (headers provided) as described below:

  1. A Method, public static int InputValue(int min, int max), to input an integer number that is between (inclusive) the range of a lower bound and an upper bound. The method should accept the lower bound and the upper bound as two parameters and allow users to re-enter the number if the number is not in the range or a non-numeric value was entered.
  1. A Method, public static bool IsValid(string id), to check if an input string satisfies the following conditions: the string’s length is 5, the string starts with 2 uppercase characters and ends with 3 digits. For example, “AS122” is a valid string, “As123” or “AS1234” are not valid strings.

Part B: Create a Book class containing the following:

  1. Two public static arrays that hold codes (categoryCodes) and descriptions of the popular book categories (categoryNames) managed in a bookstore. These codes are CS, IS, SE, SO, and MI, corresponding to book categories Computer Science, Information System, Security, Society and Miscellaneous.
  2. Data fields for book id (bookId) and book category name   (categoryNameOfBook)
  3. Auto-implemented properties that hold a book’s title (BookTitle), book’s number of pages (NumOfPages) and book’s price (Price).
  4. Properties for book id and book category name. Assume that the set accessor will always receive a book id of a valid format. For example, “CS125” and “IS334” are of valid format and also refer to known categories “Computer Science” and “Information Systems”. If the book ID does not refer to a known category, then the set accessor must retain the number and assign to the “MI” category. For example, “AS123” will be assigned as “MI123”. The category property is a read-only property that is assigned a value when the book id is set.
  5. Two constructors to create a book object:
  • one with no parameter:

public Book()

  • one with parameter for all data fields:

public Book(string bookId, string bookTitle, int numPages, double price)

  1. A ToString method, public override string ToString(), to return information of a book object using the format given in the screen shot under

Information of all Books

Part C:

Extend the application in Part A (i.e., adding code in the Program class) to become a BookStore Application by making use of the Book class and completing the following tasks:

  1. Write a Method,

           private static void GetBookData(int num, Book[] books),

to fill an array of books. The method must fill the array with Books which are constructed from user input information (which must be prompted for). Along with the prompt for a book id, it should display a list of valid book categories and call method in Part A.2 to make sure the inputted book id is a valid format. If not the user is prompted to re-enter a valid book id.

  1. After the data entry is complete, write a Method,

            public static void DisplayAllBooks(Book[] books),

to display information of all books that have been entered including book id, title, number of pages and price. This method should call the ToString method that has been created in Book class.

  1. After the data entry is complete, write a Method,

            private static void GetLists(int num, Book[] books),

to display the valid book categories, and then continuously prompts the user for category codes and displays the information of all books in the category as well as the number of books in this category.

Appropriate messages are displayed if the entered category code is not a valid code.

  1. Write the Main method that first prompts the user for the number of books that is between 1 and 30 (inclusive), by calling the method in Part A.1.

Then call method in Part C.1 to create an array of books.

Then call method in Part C.2 to display all books in the array.

Then call method in Part C.3 to allow the user to input a category code and see information of the category.

Solutions

Expert Solution

Program.java:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Program {
        public static int InputValue(int min,int max) {
                Scanner s=new Scanner(System.in);
                System.out.println("Enter the number of books:\n");
                int n=s.nextInt();
                while((n<min || n>max)) {
                        System.out.println("Enter number between "+min+" and "+max);
                        n=s.nextInt();
                }
                return n;
                }
        public static boolean IsValid(String id) {
                if(id.length()!=5) {
                        return false;
                }
                else {
                        String pattern="[A-Z]{2}[0-9]{3}";
                        Pattern r = Pattern.compile(pattern);
                        Matcher m = r.matcher(id);
                        if(m.find()) {
                                return true;
                        }
                        else {
                                return false;
                        }
                }
        }
        private static void GetBookData(int n,Book[] books) {
                Scanner s=new Scanner(System.in);
                for(int i=0;i<n;i++) {
                        System.out.println("Enter book"+(i+1)+" id:");
                        String bookId=s.nextLine();
                        boolean a = IsValid(bookId);
                        while(!a) {
                                System.out.println("Enter book"+(i+1)+" id in correct format:");
                                bookId=s.nextLine();
                                a=IsValid(bookId);
                        }
                        if(a) {
                                System.out.println("Enter the title of book"+(i+1));
                                String title=s.nextLine();
                                System.out.println("Enter the number of pages of book"+(i+1));
                                int numPages=Integer.parseInt(s.nextLine());
                                System.out.println("Enter the price of book"+(i+1));
                                double price=Double.parseDouble(s.nextLine());
                                Book b=new Book(bookId,title,numPages,price);
                                b.setBookId(bookId);
                                b.bookId=b.getBookId();
                                b.setBookCategory(bookId);
                                books[i]=b;
                        }
                        
                }
                System.out.println("\n");
                
        }
        public static void DisplayAllBooks(Book[] books) {
                System.out.println("Total books:");
                for(int i=0;i<books.length;i++) {
                        System.out.println(books[i]);
                }
                System.out.println("\n");
        }
        private static void GetLists(int num,Book[] books) {
                Scanner s1=new Scanner(System.in);
                Book b=new Book();
                System.out.println("The valid book categories are:");
                String[] cn = Book.categoryNames;
                for(int u=0;u<books.length;u++) {
                        System.out.println(books[u].bookCategory);
                }
                for(int i=0;i<num;i++) {
                        System.out.println("Enter the Category code");
                        String ccode=s1.next();
                        int count=0;
                        if(b.checkCode(ccode)) {
                                for(int j=0;j<books.length;j++) {
                                        int m=books[j].getCategoryCodeNumber(ccode);
                                        String m1=cn[m];
                                        if(books[j].bookCategory.equals(m1)) {
                                                count++;
                                                System.out.println(books[j]);
                                        }
                                }
                                if(count>0) {
                                        System.out.println("The number of books with the category code "+ccode+" are "+count);
                                }
                                else {
                                        System.out.println("No books in this category");
                                }
                                System.out.println("\n");
                        }
                        else {
                                System.out.println("Invalid code");
                        }
                }
                
        }
        public static void main(String[] args) {
                int n=InputValue(1,30);
                Book[] b=new Book[n];
                GetBookData(n,b);
                DisplayAllBooks(b);
                GetLists(5,b);
                }
        }

Screenshot:

Book.java:

public class Book {
        public static String[] categoryCode= {"CS","IS","SE","SO","MI"};
        public static String[] categoryNames= {"Computer Science","Information System","Security","Society","Miscellaneous"};
        String bookId;
        String bookCategory;
        String bookTitle;
        int numPages;
        double price;
        public Book() {
                }
        public Book(String bookId, String bookTitle, int numPages, double price) {
                this.bookId=bookId;
                this.bookTitle=bookTitle;
                this.numPages=numPages;
                this.price=price;
        }
        public void setBookId(String bookId) {
                String s=bookId.substring(0,2);
                int flag=0;
                for(int i=0;i<categoryCode.length;i++) {
                        if(s.equals(categoryCode[i])) {
                                flag=1;
                                break;
                        }
                }
                if(flag==0) {
                        bookId="MI"+bookId.substring(2,5);
                }
                this.bookId=bookId;
        }
        public String getBookId() {
                return bookId;
        }
        
        public String getBookCategory() {
                return bookCategory;
        }
        public void setBookCategory(String bookId) {
                String s=bookId.substring(0,2);
                bookCategory=categoryNames[4];
                for(int i=0;i<categoryCode.length;i++) {
                        
                        if(categoryCode[i].equals(s)) {
                                bookCategory=categoryNames[i];
                        }
                }
        }
        public boolean checkCode(String c) {
                for(int i=0;i<categoryCode.length;i++) {
                        if(categoryCode[i].equals(c)) {
                                return true;
                        }
                }
                return false;
        }
        public int  getCategoryCodeNumber(String  c) {
                for(int i=0;i<categoryCode.length;i++) {
                        if(categoryCode[i].equals(c)) {
                                return i;
                        }
                }
                return 0;       
        }
        public String getBookTitle() {
                return bookTitle;
        }
        public void setBookTitle(String bookTitle) {
                this.bookTitle = bookTitle;
        }
        public int getNumPages() {
                return numPages;
        }
        public void setNumPages(int numPages) {
                this.numPages = numPages;
        }
        public double getPrice() {
                return price;
        }
        public void setPrice(double price) {
                this.price = price;
        }
        @Override
        public String toString() {
                return "Book [bookId=" + bookId + ", bookCategory=" + bookCategory + ", bookTitle=" + bookTitle + ", numPages="
                                + numPages + ", price=" + price + "]";
        }
}

Screenshot:

Screenshot of the output:


Related Solutions

Write a program in java that does the following: Create a StudentRecord class that keeps the...
Write a program in java that does the following: Create a StudentRecord class that keeps the following information for a student: first name (String), last name (String), and balance (integer). Provide proper constructor, setter and getter methods. Read the student information (one student per line) from the input file “csc272input.txt”. The information in the file is listed below. You can use it to generate the input file yourself, or use the original input file that is available alone with this...
write program that develop a Java class Dictionary to support the following public methods of an...
write program that develop a Java class Dictionary to support the following public methods of an abstract data type: public class Dictionary { // insert a (key, value) pair into the Dictionary, key value must be unique, the value is associated with the key; only the last value inserted for a key will be kept public void insert(String key, String value); // return the value associated with the key value public String lookup(String key); // delete the (key, value) pair...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services should have two private attributes numberOfHours and ratePerHour of type float. Class Supplies should also have two private attributes numberOfItems and pricePerItem of type float. For each class, provide its getter and setter functions, and a constructor that will take the two of its private attributes. Create method calculateSales() for each class that will calculate the cost accrued. For example, the cost accrued for...
Part A Java netbeans ☑ Create a project and in it a class with a main....
Part A Java netbeans ☑ Create a project and in it a class with a main. We will be using the Scanner class to read from the user. At the top of your main class , after the package statement, paste import java.util.Scanner; As the first line inside your main method, paste Scanner scan = new Scanner(System.in); Remember when you are getting a value from the user, first print a request, then use the Scanner to read the right type...
HOMEWORK PROJECT #1 – SHOPPING CART Part I. Create two files to submit: ItemToPurchase.java – Class...
HOMEWORK PROJECT #1 – SHOPPING CART Part I. Create two files to submit: ItemToPurchase.java – Class Definition ShoppingCartPrinter.java – Contains main() method Build the ItemToPurchase class with the following specifications: Specifications Description ItemToPurchase(itemName) itemName – The name will be a String datatype and Initialized in default constructor to “none”. ItemToPurchase(itemPrice) itemPrice – The price will be integer datatype and Initialized in default constructor to 0. ItemToPurchase(itemQuantity) itemQuantity – The quantity will be integer datatype Initialized in default constructor to 0....
Part 1 – Create a Stock Class Write a class named Stock. Stock Class Specifications Include...
Part 1 – Create a Stock Class Write a class named Stock. Stock Class Specifications Include member variables for name (string), price (double), shares (double). Write a default constructor. Write a constructor that takes values for all member variables as parameters. Write a copy constructor. Implement Get/Set methods for all member variables. Implement the CalculateValue function. This function should multiply the prices by the shares and return that value. Use the following function header: double CalculateValue(). Add a member overload...
Write a python program using the following requirements: Create a class called Sentence which has a...
Write a python program using the following requirements: Create a class called Sentence which has a constructor that takes a sentence string as input. The default value for the constructor should be an empty string The sentence must be a private attribute in the class contains the following class methods: get_all_words — Returns all the words in the sentence as a list get_word — Returns only the word at a particular index in the sentence Arguments: index set_word — Changes...
write the program in java. Demonstrate that you understand how to use create a class and...
write the program in java. Demonstrate that you understand how to use create a class and test it using JUnit Let’s create a new Project HoursWorked Under your src folder, create package edu.cincinnatistate.pay Now, create a new class HoursWorked in package edu.cincinnatistate.pay This class needs to do the following: Have a constructor that receives intHours which will be stored in totalHrs Have a method addHours to add hours to totalHrs Have a method subHours to subtract hours from totalHrs Have...
Write a program to create a bank account and to process transactions. Call this class bankAccount...
Write a program to create a bank account and to process transactions. Call this class bankAccount A bank account can only be given an initial balance when it is instantiated. By default, a new bank account should have a balance of 0. A bank account should have a public get method, but no public set method. A bank account should have a process method with a double parameter to perform deposits and withdrawals. A negative parameter represents a withdrawal. It...
Write a Java program to process the information for a bank customer.  Create a class to manage...
Write a Java program to process the information for a bank customer.  Create a class to manage an account, include the necessary data members and methods as necessary.  Develop a tester class to create an object and test all methods and print the info for 1 customer.  Your program must be able to read a record from keyboard, calculate the bonus and print the details to the monitor.  Bonus is 2% per year of deposit, if the amount is on deposit for 5 years...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT