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

Create a Project and a Class called “FinalGrade” Write a Java program to compute your final...
Create a Project and a Class called “FinalGrade” Write a Java program to compute your final grade for the course. Assume the following (you can hard-code these values in your program). Assignments are worth 30% Labs are worth 40% Mid-term is worth 15% Final is worth 15% Ask for the grades in each category. Store them in a double variable. Print out the final percentage grade.           For example, Final Grade Calculation Enter percentage grades in the following order. Assignments,...
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...
Program in Java Create a stack class to store integers and implement following methods: 1- void...
Program in Java Create a stack class to store integers and implement following methods: 1- void push(int num): This method will push an integer to the top of the stack. 2- int pop(): This method will return the value stored in the top of the stack. If the stack is empty this method will return -1. 3- void display(): This method will display all numbers in the stack from top to bottom (First item displayed will be the top value)....
Program in Java Create a queue class to store integers and implement following methods: 1- void...
Program in Java Create a queue class to store integers and implement following methods: 1- void enqueue(int num): This method will add an integer to the queue (end of the queue). 2- int dequeue(): This method will return the first item in the queue (First In First Out). 3- void display(): This method will display all items in the queue (First item will be displayed first). 4- Boolean isEmpty(): This method will check the queue and if it is empty,...
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...
3) Create a Java program that uses NO methods, but use scanner: Write a program where...
3) Create a Java program that uses NO methods, but use scanner: Write a program where you will enter the flying distance from one continent to another, you will take the plane in one country, then you will enter miles per gallon and price of gallon and in the end it will calculate how much gas was spend for that distance in miles. Steps: 1) Prompt user to enter the name of country that you are 2) Declare variable to...
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....
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT