1

I am trying to create a driver class using array list of objects and it requires me to :

  • Read the book title from the user
  • Read the book ISBN from the user
  • Read the book in stock quantity from the user
  • program should continue to read the book information from the user until all the entries from the user for all the fields are blank or zero.
  • program will store valid book objects into an ArrayList (only valid objects)
  • Your program will then print the list all the "valid" Books entered by the user in the reverse order in which the books were entered.
  • As the user is entering information, the program should give feedback such as reporting that an item has been added to the ArrayList, or reporting any errors found.
  • Books with invalid entries were not added to the ArrayList, therefore they will not be printed when the ArrayList is printed

Here is my current code so far for my driver: (I'm a bit newb at this so ) edited: with the answer given

Here is what I got now

 import java.io.*;
 import java.util.*;

public class Bookstore2{
 
    
        
   public static void main(String arg[ ]) throws Exception{
   
      Scanner sc = new Scanner(System.in);
      int isbn=0;
      int quantity = 0;
      String title = "";
      Book oneBook;
      List<Book> bookList = new ArrayList<Book>(); //here  
    
     while(true){
    System.out.print("Enter title: ");
    title = sc.nextLine( );
    sc = new Scanner(System.in);
    System.out.println();
    System.out.print("Enter isbn: ");
    isbn = sc.nextInt( );
    sc = new Scanner(System.in);
    System.out.println();
    System.out.print("Enter quantity: ");
    quantity = sc.nextInt( );
    sc = new Scanner(System.in);
    sc = new Scanner(System.in);
    System.out.println();   

 // WRITE YOUR VALIDATION CODE HERE 
 // Change condition according to your requirements.
    if(isbn !=0 && quantity != 0 && title != null && title != "")
    {
        oneBook = new Book(title, isbn, quantity);
    bookList.add(oneBook); //create a list in main
    System.out.println("Book added in the list."); 
    }
    else 
    {
        System.out.println("Book not added");
         break;
       }

}
  for(int i = bookList.size()-1; i >= 0; i--){
    System.out.println(bookList.get(i));
    }   
    }  //main method
}   //class

error now averted but it's not utilizing both my exception and book class it seems like

Here is my class and my exception that will be running with the new driver class

-----Class

public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;

public Book (String title, int isbn, int quantity)throws BookException{     
//constructors

     setTitle(title);
     setIsbn(isbn);
     setQuantity(quantity);

   }
public String toString( ){ //toString Method

    String s = "";
    s = s + "Title: " + this.title + "\nISBN: " + this.isbn +   "\nQuantity: " + this.quantity + "\n";
    return s;

    }

public String getTitle( ){
    return this.title;
    }
public int getisbn( ){
    return this.isbn;
    }
public int getquantity( ){  
    return this.quantity;
    }

//mutator methods
public void setTitle(String newtitle )throws BookException{
    if(newtitle.length()<1){
    BookException be = new BookException( );
    be.setMessage("Title cannot be blank");
    throw be;
    }
    else{
    this.title=newtitle;
    }
}

public void setIsbn(int newisbn)throws BookException{
    if (isbn <= 1000 || isbn >= 10000) {
    this.isbn = newisbn;
    }
    else{
    BookException be = new BookException( );
    be.setMessage("ISBN should be between 1000 and 10000.");
    throw be;
    }
}

public void setQuantity(int newquantity)throws BookException{
   if(newquantity>=0){
   this.quantity = newquantity;
    }
   else{
    BookException be = new BookException( );
    be.setMessage("Quantity can't be a negative number.");
    throw be;
     }
  }

}

------Exception Class

public class BookException extends Exception {
    //instance variable
    private String message = "";

    public void setMessage(String newMessage) {
        this.message = newMessage;
    }

    public String getMessage() {
        return this.message;
    }
}
aldz24
  • 65
  • 8
  • Where´s the `List`? and what´s your exact problem? i can´t figure it out from the question. – SomeJavaGuy Dec 03 '15 at 09:27
  • I'm creating a driver class using array of book objects and as stated above i need to follow the requirments .. – aldz24 Dec 03 '15 at 09:33
  • My exact question is : How Do I make a driver class that follows the instructions on top using arrays that is stated ? i already listed my book class and exception class .. I just need the driver class but i don't know what to put next – aldz24 Dec 03 '15 at 09:36
  • Am i forgetting my arraylist or something ? I'm just following what the instruction says ;_; – aldz24 Dec 03 '15 at 09:52
  • They want me to implement a driver class with array list of book objects ? How do I do that ? – aldz24 Dec 03 '15 at 09:54
  • 1
    change ``isbn != null`` to ``isbn != 0``, as primitive variables cannot be ``null`` – Binkan Salaryman Dec 03 '15 at 10:23
  • @GustavoCinque Abusing ``Integer`` as nullable ``int`` type... better define some constant value e.g. ``Integer.minValue`` to have the meaning "no value set", initialize and compare with it instead. Beside that, calling ``Integer#intValue()`` should not be necessary, as autoboxing and -unboxing takes place. – Binkan Salaryman Dec 03 '15 at 10:27
  • works now but my the driver class is not responding to the book class and exceptions class that i made – aldz24 Dec 03 '15 at 10:40

3 Answers3

3

First of all use: while(true) loop to iterate until user entered 0 for all the field.

while(true)
{
   // Scanner Code i.e. read input from the user.
   if(//check all the inputs)
   {
       //create a new book and insert it into array list
   }
   else
   {
     // If input is 0, break from the loop
   }
}

Secondly, Never perform validation in your bean class. Create a separate class or method to validate the inputs. After, input validation only then create a new object.

Hope this will help you.

The correct code :

     sc = new Scanner(System.in);
    while(true){
    System.out.print("Enter title: ");
    title = sc.nextLine( );
           System.out.println();
    System.out.print("Enter isbn: ");
    isbn = sc.nextInt( );
    System.out.println();
    System.out.print("Enter quantity: ");
    quantity = sc.nextInt( );
    System.out.println();   

 // WRITE YOUR VALIDATION CODE HERE 
 // Change condition according to your requirements.
    if(isbn !=0 && quantity != 0 && title != null && title != "")
    {
        oneBook = new Book(title, isbn, quantity);
    bookList.add(oneBook); //create a list in main
    System.out.println("Book added in the list."); 
    }
    else 
    {
        System.out.println("Book not added");
         break;
       }

}
  for(int i = bookList.size()-1; i >= 0; i--){
    System.out.println(bookList.get(i));
    }
Ashish Ani
  • 324
  • 1
  • 7
  • +1 for simple loop instructions - infinite loops (``while(true)``) with ``break``s, ``for``-i, reversed ``for``-i and ``for``-each loops cover most repeating problems and are easy to read, understand and change. – Binkan Salaryman Dec 03 '15 at 10:32
  • I might consider your option Ash ...how would it look like exactly in code form? base from my codes? – aldz24 Dec 03 '15 at 10:33
  • thank you ! I edited it using your codes but it's not utilizing my book class and exception class in the bottom it seems like..i'm trying to make them all 3 work together. also would adding inputmismatchexception necesarry in the driver class or would the book class take care of that? – aldz24 Dec 03 '15 at 10:47
  • Book class is used when input is correct and you are creating a new book class object. And, throw an exception when user entered a invalid values. – Ashish Ani Dec 03 '15 at 10:49
  • says no main methods, applets, or MIDLETS found in file if i run the book class – aldz24 Dec 03 '15 at 10:51
  • why you are trying to run book class, you have to run BookStore2 class as that class contains a main method – Ashish Ani Dec 03 '15 at 10:54
  • 1
    Not sure if you put it the many ``sc = new Scanner(System.in);`` lines, but: [**don't create multiple scanners on System.in**](http://stackoverflow.com/a/4232614/3071928) – Binkan Salaryman Dec 03 '15 at 11:22
  • @BinkanSalaryman yes, we have to create only one sc = new Scanner(System.in); . Thanks.... – Ashish Ani Dec 03 '15 at 11:24
0

You posted :

while(title != null || title.equals("0") || isbn != null || isbn != 0 || quantity

isbn is of int type i.e. primitive type how can we compare it with a null. quantity is also of int type. Default value of an int i.e. primitive type is 0. And, primitive type can never be compared with null.

Ashish Ani
  • 324
  • 1
  • 7
0

Since there is so much confusion on the code, here is a complete solution to the task:

Bookstore.java:

public class Bookstore {
    static final Scanner in = new Scanner(System.in);
    static List<Book> books = new ArrayList<>();

    public static void main(String arg[]) throws Exception {
        while (true) {
            // read book information
            Book book = new Book();
            System.out.print("Enter title: ");
            book.title = in.nextLine();
            System.out.println();

            System.out.print("Enter ISBN: ");
            book.isbn = readInt();
            System.out.println();

            System.out.print("Enter quantity: ");
            book.quantity = readInt();
            System.out.println();

            // exit condition: "blank book" entered
            if (book.title.isEmpty() && book.isbn == 0 && book.quantity == 0) {
                System.out.println("Goodbye!");
                break;
            }

            //validate and add book
            try {
                validateBook(book);
                books.add(book);
                System.out.println("Book successfully added to the list.");
            } catch (IllegalStateException ex) {
                System.err.println("Book is not valid: " + ex.getMessage());
                continue;
            }

            // print book list
            for (int i = books.size() - 1; i >= 0; i--) {
                System.out.println(books.get(i));
                System.out.println();
            }
        }
    }

    static int readInt() {
        while (true) {
            String input = in.nextLine();
            if(input.isEmpty()) {
                return 0;
            }
            try {
                return Integer.parseInt(input);
            } catch (NumberFormatException ex) {
                System.err.println("Expected a valid integer: " + input);
            }
        }
    }

    static void validateBook(Book book) {
        if (book.title == null || book.title.isEmpty()) {
            throw new IllegalStateException("Book title must not be blank.");
        }
        if (book.isbn < 1000 || book.isbn > 10000) {
            throw new IllegalStateException("Book ISBN must be between 1000 and 10000.");
        }
        if (book.quantity < 0) {
            throw new IllegalStateException("Book quantity must be positive.");
        }
    }
}

Book.java:

public class Book {
    public String title;
    public int isbn;
    public int quantity;

    @Override
    public String toString() {
        return String.join("\n",
                "Title: " + title,
                "ISBN: " + isbn,
                "Quantity: " + quantity
        );
    }
}
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
  • while I do wanna use your bookstore suggestion, I have to match it with my book and exception class that i have :( and it's not picking up the exceptions from my other class – aldz24 Dec 03 '15 at 22:02