Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 23 of 23

Thread: Simple Library Program / Need feedback.

  1. #1
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Simple Library Program / Need feedback.

    Hi everyone.
    I have a java programming project, a simple library system:
    User has to add books, borrow books, remove books, return books, clear library and exit the library.
    This is University assignment, so i'm not asking you guys to write it for me. I'm simply asking for some feedback on structure and logic.
    I am kinda a beginner, been programming for 3-4 months, so please don't suggest anything way too complex for me to grasp, although i will try my best to learn new methodologies and concepts.

    The code is not all written yet, i only covered so far the following parts:
    1- add a book to the library.
    2- display the books.
    3- remove a book.
    4- repeat the previous functions as many times as needed.
    5- exit the program.

    This thread is aimed simply at pointing me in the right direction, not solving it for me.
    All feedback is greatly appreciated
    Here is the code:

     
    package library;
     
    import java.util.ArrayList;
    import java.util.InputMismatchException;
    import java.util.Scanner;
     
    public class Book {
     
    	public String title;
    	public String author;
    	public String publisher;
    	public String publicationYear;
    	public String status;
    	public String borrower;
    	public String borrowDate;
    	public String returnDate;
     
    	public String status1 = "Available";
    	public String status2 = "Borrowed";
    	public int BookChoice;
     
     
    	static ArrayList<String> UserList = new ArrayList<String>();
    	static ArrayList<Book> BookList = new ArrayList<Book>();
     
    	static int choice ;
     
    	static Scanner userInput = new Scanner(System.in);
    	static Scanner choiceInput = new Scanner(System.in);
    	/*
    	 * Book Constructor:
    	 */
     
    	/**
    	 * ===================================================================================================
    	 * Class Methods here:
    	 * ===================================================================================================
    	 */
     
    	public static void displayFirstMenu(){
    		System.out.println(">########################################################################");
    		System.out.println("> Choose one of the options below by typing the corresponding number: ");
    		System.out.println(">====================================================================");
    		System.out.println("2- Add a book to the Library.");
    		System.out.println("6- Blow up library.");
    		System.out.println("7- Back to main menu.");
    		System.out.println("0- Exit.");
    		System.out.println(">########################################################################");
    		System.out.println("> Enter your option here: ");
    		choice = choiceInput.nextInt();//User inputs a choice (integer).
     
    	}
     
    	public static void displaySecondMenu(){
    		System.out.println(">########################################################################");
    		System.out.println("> Choose one of the options below by typing the corresponding number: ");
    		System.out.println(">====================================================================");
    		System.out.println("1- Check library list.");
    		System.out.println("2- Add a book to the Library.");
    		System.out.println("3- Borrow a book.");
    		System.out.println("4- Return a book.");
    		System.out.println("5- Delete a book.");
    		System.out.println("6- Blow up library.");
    		System.out.println("7- Back to main menu.");
    		System.out.println("0- Exit.");
    		System.out.println(">########################################################################");
    		System.out.println("> Enter your option here: ");
    		choice = choiceInput.nextInt();//User inputs a choice (integer).
     
    	}
     
    	public String displayBook(){
     
    		String BookInfo = "----------------------------"+
    						"\nTitle:.................."+title+
    						"\nAuthor:................."+author+
    						"\nPublisher:.............."+publisher+ 
    						"\nPublicationYear:........"+publicationYear+
    						"\nStatus:................."+status+
    						"\nBorrower:..............."+borrower+
    						"\nDate Borrowed:.........."+borrowDate+
    						"\nReturn date:............"+returnDate+
    						"\n----------------------------";
    		return BookInfo;	
    	}
     
    	public void createBook(){
    		System.out.println("> Enter the title of the book: ");
    		title = userInput.nextLine();
     
    		System.out.println("> Enter the author of the book: ");
    		author = userInput.nextLine();
     
    		System.out.println("> Enter the publisher of the book: ");
    		publisher = userInput.nextLine();
     
    		System.out.println("> Enter the publication year of the book: ");
    		publicationYear = userInput.nextLine();
     
    		borrower = "nobody";
    		borrowDate = "none";
    		returnDate = "none";
     
    		status = "Available";
    	}
     
    	public void addBook(){
    		Book newBook = new Book(); //create new book object with status "Available."
    		newBook.createBook();
    		BookList.add(newBook);//add the book to the BookList ArrayList.
    		System.out.println("---------------------------------------------------------");
    		System.out.println("> You have successfully added the book to the library!\n");
    		System.out.println("---------------------------------------------------------");	
    	}
     
    	public void displayBookList(){
    		if (BookList.size() == 0){//If the library is empty, it goes back to main menu and choice.
    			System.out.println(">-------------------------------------------------------------");
    			System.out.println("> There Library is Emply! Please add a book first!\n");
    			System.out.println(">-------------------------------------------------------------");
    			Book.displayFirstMenu();//Display to main menu.
    			choice = choiceInput.nextInt();//Register new choice.
     
    		} else {					
    			for (int i = 0; i < BookList.size(); i++){
    				System.out.printf("\n>-----------Book Index: [%s]---------------------------------\n",i+1);
    				System.out.println(BookList.get(i).displayBook());	
    				System.out.println(">-------------------------------------------------------------");
    			}//End of For Loop.			
    		}// End of Else Statement.			
    	}//End of if Statement.
     
    	public void borrowBook(){
    		System.out.println("---------------------------------------------------------");
    		System.out.println("> Here are all the books registered in the library: ");
    		System.out.println("---------------------------------------------------------");		
    		displayBookList();
     
    		borrowLoop1:
    		while(choice == 3){
    			System.out.println("\n\n> Choose an available book from the above list and write down it's index number: ");
    			BookChoice = choiceInput.nextInt()-1;//register user's book choice.
    			if(BookChoice > BookList.size()){
    				System.out.println("> The number of the book you entered is not in the list!");
    				choice = 7;
    			}else if(BookChoice <= BookList.size()){
    				break borrowLoop1;
    			}
    		}		
     
    		borrowLoop2:
    		while(choice == 3){
    			//Check if the book to be borrowed is available.
    			if (BookList.get(BookChoice).status.equalsIgnoreCase(status1) && BookList.size() >= BookChoice){
    				//Print the borrowed book information and change the book status to borrowed.
    				BookList.get(BookChoice).status = "Borrowed";
    				System.out.printf("\n> You have chosen the following book: %s\n", BookList.get(BookChoice).displayBook());
     
    				//add the user name to the book borrower variable:
    				BookList.get(BookChoice).borrower = borrower;
    				BookList.get(BookChoice).borrowDate = "Today.";
    				BookList.get(BookChoice).returnDate = "In two weeks.";
    				System.out.println("> You have to return the book in two weeks!");
    				choice = 7;
    				break borrowLoop2;
     
    			}else if(BookList.get(BookChoice).status.equalsIgnoreCase(status2) && BookList.size() >= BookChoice){
    				System.out.println("> The Book you are trying to borrow is unavailable!");
    				choice = 7;
    				break borrowLoop2;
    			}else if(BookChoice > BookList.size()-1){
    				System.out.println("> The number you entered in not in the list!");
    				choice = 7;
    				break borrowLoop2;
    			}
    		}
    	}
     
     
    	public void returnBook(){
    		System.out.println("> Enter the Title of the book you want to return: ");
    		String returnBookTitle = userInput.nextLine();
    		int x = 0;
    		while (x < BookList.size()){//Search for the book by title, if it exists change it's status,
    									//it's borrower and borrowDate.
    			if (BookList.get(x).title.equalsIgnoreCase(returnBookTitle)){
    				BookList.get(x).status = "Available";
    				BookList.get(x).borrower = "none";
    				BookList.get(x).borrowDate = "none";
    				System.out.println("> You have successfully returned the book to the library!");
    				Book.displayFirstMenu();//Display main menu.
    				choice = choiceInput.nextInt();//Register new choice.
    				break;//if a title is found, break out of the loop and display choice menu.
    			}
    			x = x+1;
    		}//end of while loop.
    		x = 0;
    		while (x < BookList.size() && BookList.size() > 0){//Search for the title and if it's not in the library, 
    									//print a warning message to the user, and register a new menu choice.
    			if (BookList.get(x).title.equalsIgnoreCase(returnBookTitle)){
    		}else{
    			System.out.println("> The are no books with this title in the library." +
    					" Please make sure the title is spelt correctly or choose to add the book " +
    					"to the library from the main menu. ");
    			Book.displayFirstMenu();//Display main menu.
    			choice = choiceInput.nextInt();//Register new choice.					
    			}//End of else statement.
    		}//End of while loop.
    		Book.displayFirstMenu();//Display main menu.
    		choice = choiceInput.nextInt();//Register new choice.
    	}
     
     
    	public void removeBook(){
    		int i = 0;
    		System.out.println("---------------------------------------------------------");
    		System.out.println("> Here are all the books registered in the library: ");
    		System.out.println("---------------------------------------------------------");
     
    		while (i < BookList.size() && BookList.size() > 0){//show the user the list of all the books
    			System.out.printf("\n> Book number %s:\n%s",i+1,BookList.get(i));
    			i = i+1;
    		}//end of while loop.
     
    		System.out.println("\n\n> Choose an available book from the above list and write down it's number: ");
    		int BookChoice = choiceInput.nextInt()-1;//register user's book choice.
     
    		while(choice == 5){
    			try{
    				if (BookChoice > 0 && BookChoice < BookList.size() && BookList.get(BookChoice).status.equalsIgnoreCase("Available")){//Check if the book to be borrowed is available.
    					//Print the borrowed book information and change the book status to borrowed.
    					BookList.remove(BookChoice);
    					System.out.printf("\n> You have chosen to delete the following book: %s\n", BookList.get(BookChoice));
    					System.out.printf("\n> The Book %s is deleted.\n", BookList.get(BookChoice));
    					choice = 7;
    				}
    			}catch(InputMismatchException error){
    				System.out.println("<ERROR> Please enter a number of book from the list: ");
    				choiceInput.nextInt();
    				choice = 5;
    			}catch(IndexOutOfBoundsException error){
    				System.out.println("<ERROR> Please enter a number of book from the list: ");
    				choice = 5;
    			}
    		}		
    	}
     
     
    	public void emptyLibrary(){
    		System.out.println("> WARNING < You have chosen to delete all books in the library! ");
    		System.out.println("> Are you sure?? Enter yes or no: ");
    		String confirmation = userInput.nextLine();
    		try{
    			if(confirmation.equalsIgnoreCase("yes")){
    				System.out.println("> Library is being deleted...");
    				BookList.clear();
    				System.out.println("> Library is Empty!");
    				choice = 7;
    			}
    		}catch(InputMismatchException error){
    			System.out.println("<ERROR> Make sure you spell yes or no correctrly: ");
    			choice = 6;
    		}
    	}
     
     
    	public void addUser(){
    		System.out.println("> Enter your name: ");
    		borrower = userInput.nextLine();
    		UserList.add(borrower);	//Add the userName to the UserList arrayList.	
    	}
     
    	public void run(){
     
    		System.out.println("@TEST@ <<< 1 >>>>");
     
    		addUser();
    		System.out.println("@TEST@ <<< 2 >>>>");
     
    		Book.displayFirstMenu();//Displays the main menu and ask for choice.
     
    		System.out.println("@TEST@ <<< 3- Entering main while loop...>>>>");
     
    		exit:
     
    			while(choice != 0){	
    				try{
    //Choice 1:					
    					if(choice == 1 && BookList.size() > 0){
     
    						displayBookList();
    						choice = 7;
    					}
     
    					if(choice == 1 && BookList.size() == 0){
    						System.out.println("<ERROR> Library is empty! Please add a Book first!");
    						choice = 7;
    					}
    //Choice 2:					
    					if(choice == 2){
    						//createBook();
    						addBook();
    						displaySecondMenu();
    					}
    //Choice 3:					
    					if(choice == 3){
    						if(BookList.size() > 0){
    							borrowBook();							
    						}						
    					}
    //Choice 4:					
    					if(choice == 4){
    						returnBook();
    					}
    //Choice 5:					
    					if(choice == 5){
    						removeBook();
    						try{
    							if(BookList.size() > 0){
    								displaySecondMenu();
    							}
    						}catch(IndexOutOfBoundsException error){
    							System.out.println("<ERROR> The array is Empty! Please add a book first!");
    							choice = 7;
    							//break; //Test the Break statement!!!!!!!!!!!!!!!!!!!
    						}
    					}
    //Choice 6:					
    					if(choice == 6){
    						emptyLibrary();						
    					}
    //Choice 7:					
    					if(choice == 7){
    						if(BookList.size() > 0){
    							displaySecondMenu();
    						}else if(BookList.size() == 0){							
    							displayFirstMenu();
    						}
    					}
    //Choice 0:					
    					if(choice == 0){
    						break exit;
    					}
    				}catch(InputMismatchException error){				
    					System.out.println("@TEST@ <<< 5- Breaking from main while loop... >>>>");
    					break exit;
    				}
     
    			}//end of while loop.
     
    		System.out.println("####  You have Exited the Library!  ####");
     
    		}//End of run() method.
     
     
    	/**
    	 * ===================================================================================================
    	 * End of Class Methods.
    	 * ===================================================================================================
    	 */
     
    	public static void main(String[] args){
     
    		System.out.println("> Welcome to the library!");
     
    		Book newBook = new Book();
    		newBook.run();
     
    	}//End of Main Method.
     
    }
    Last edited by ziplague; March 18th, 2012 at 01:15 PM.

  2. The Following User Says Thank You to ziplague For This Useful Post:

    blackoutro (March 19th, 2014)


  3. #2
    Member
    Join Date
    Feb 2012
    Posts
    58
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: Simple Library Program / Need feedback.

    hi,

    you have done a good job! I haven't looked deeper into your code yet, however I have a comment:
    - Avoid writing monolithic application (which is a program which has only one source file for everything), because such coding will be very hard to extend/develop further when the program becomes bigger. Instead, you should separate the program into smaller classes, for example you can at least separate the current program into Book class and Library class.

  4. The Following User Says Thank You to Bob_Sadarka For This Useful Post:

    ziplague (March 19th, 2012)

  5. #3
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Simple Library Program / Need feedback.

    I have a half hour to spare for a code review for a fellow student. I do not have the time to test anything so I am assuming that everything works as expected. Don't take any of my comments too critically because your code looks pretty good. As does your structure and use of methods.

    • Those primitive properties should be private, not public. Use public when you want to expose the properties to other methods and cannot be bothered to write getters/setters
    • Those other global properties like the ArrayLists should also be private, not static. Static properties are variables that belong to the class and not the object. You would only use this modifier when you require the variable to be shared across separate instances of the object and I see no reason for it here.
    • How are you dealing with invalid user input? The first thing your lecturer is going to do is to break your code by trying to put something invalid as a menu choice.
    • Closely related to the above point - I would avoid having choice as a global variable. It will make the flow of control very difficult to handle as there will be a lot of states both valid and invalid your program can be in. Instead, consider returning an int from those menu methods. The advantage of this is you can deal with invalid input at it's source.
    • Those menu methods should not be static (as above).
    • Since you are using generics with your ArrayLists you can use the for each loop to iterate over each item in the collection. It is clearly and less buggy to say for (Book b : BookList) { }
    • When you find yourself writing an whole lot of if's from the same variable (if number == 1, if number == 2, etc, etc) consider using a switch statement. Again, it is clearer and less likely to be buggy.
    • A bit nitpicky, but stick to the camelCase naming convention with variables like BookList (just do a find and replace)
    • Now this brings me to the biggest problem and it's the one Bob_Sadarka hinted at. Do you see the variable BookList is actually a collection of objects of the class Book which is the class it exists in. What I am saying is that BookList is a member of it's own class. You would only use this if you were writing a singleton and never in this way. I can kind of see that it works and does what you were expecting it to but the logic is all backwards and it will lead to all sorts of hard to debug problems. I am guessing this is why you defined it as static; to prevent a syntax error and in this scenario you were only hiding the problem. I would count this as the biggest issue with the code and as you can tell it is kind of hard for me to explain it clearly. Fixing this would require restructuring the code, commonly called refactoring. If you choose to refactor consider this; java is an OO language. Think objects. What do you have? A Book has a title, author, etc. A library has a collection of books and a way of loaning, returning books, adding new books, etc, etc.
    • And finally, remember to remove those TEST printlns before you submit.


    Again, just let me repeat; don't let anything I have said get you down - you have a good coding style and understanding of the concepts and you will make a reasonable programmer if you choose to stick with it and constantly improve.

    Hope this was of some help.


    Chris

  6. The Following 2 Users Say Thank You to ChristopherLowe For This Useful Post:

    Tjstretch (March 19th, 2012), ziplague (March 19th, 2012)

  7. #4
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    "How are you dealing with invalid user input? The first thing your lecturer is going to do is to break your code by trying to put something invalid as a menu choice."
    i know i broke it myself, i knew this problem was there from the beginning, i just left it for later fixing. I fixed it today with this method:
    public static void choicePrompt(){		
    		while(choiceCheck){		
    			try{
    				choice = choiceInput.nextInt();//User inputs a choice (integer).				
    			}catch(InputMismatchException error){
    				System.out.println("<ERROR> Please enter a number from the list!!");				
    			}
    			choiceCheck = false;
    		}
    	}

    As for the static stuff and writing everything in one file, the reason is that i encountered lots of warning(cannot refer to a static method in a non static method and the way around) so i decided to put everything in one class. I will try to change this when the program is fully working.

    Thanks a lot for your time, really appreciate the input
    I uploaded the code in a haste, did not check comments and test, sorry for that.

    "Hope this was of some help." This was of great help, thank you very much

  8. #5
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    Quote Originally Posted by Bob_Sadarka View Post
    hi,

    you have done a good job! I haven't looked deeper into your code yet, however I have a comment:
    - Avoid writing monolithic application (which is a program which has only one source file for everything), because such coding will be very hard to extend/develop further when the program becomes bigger. Instead, you should separate the program into smaller classes, for example you can at least separate the current program into Book class and Library class.
    Thanks for pointing that out, i was planning on separating the parts at the end, it's just that i had lots of "static/non-static accessing methods and instances" problems at first so i just accepted the eclipse auto fix suggestions, i had a class for book and another one for library with the main method.

  9. #6
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    About the "if" choice statements, i'm familiarizing myself with the switch statement that was suggested, i never used it before. i can already see how it could reduce the code considerably, i just don't know how to use it yet. I'll try to work it out and re-post the new code when it's done.

  10. #7
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Simple Library Program / Need feedback.

    Quote Originally Posted by ziplague View Post
    ... I fixed it today with this method ...
    This does not really address the issue. How does a InputMismatchException get thrown? How does the user correct the problem after they have received the message that the input is invalid?

    A better option would be to create a method that asks for user input in a range of values and returns a correct integer. It is reusable and fail safe. I posted an article on Valid user input that uses recursion to accomplish this. Take a look and write your own method to suit.

    Quote Originally Posted by ziplague View Post
    As for the static stuff and writing everything in one file, the reason is that i encountered lots of warning(cannot refer to a static method in a non static method and the way around) so i decided to put everything in one class. I will try to change this when the program is fully working.
    That is my point. Those warnings are a symptoms of a much larger problem which you have treated without addressing the underlying issue. Kind of like treating cancer by prescribing pain killers.

    After seeing plenty of *really* bad programming assignments I can tell you (without ANY guarantees) that you will probably pass with what you have. But asking for a code review tells me you want to develop your programming skills and do better than the bear minimum. That is why I helped you out and the big suggestion I made was to refactor into multiple classes. From experience I can tell you with absolute certainty that these things are easier to deal with if you deal with them early, just like cancer.

  11. The Following User Says Thank You to ChristopherLowe For This Useful Post:

    ziplague (March 19th, 2012)

  12. #8
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    Quote Originally Posted by ChristopherLowe View Post
    This does not really address the issue. How does a InputMismatchException get thrown? How does the user correct the problem after they have received the message that the input is invalid?

    A better option would be to create a method that asks for user input in a range of values and returns a correct integer. It is reusable and fail safe. I posted an article on Valid user input that uses recursion to accomplish this. Take a look and write your own method to suit.


    That is my point. Those warnings are a symptoms of a much larger problem which you have treated without addressing the underlying issue. Kind of like treating cancer by prescribing pain killers.

    After seeing plenty of *really* bad programming assignments I can tell you (without ANY guarantees) that you will probably pass with what you have. But asking for a code review tells me you want to develop your programming skills and do better than the bear minimum. That is why I helped you out and the big suggestion I made was to refactor into multiple classes. From experience I can tell you with absolute certainty that these things are easier to deal with if you deal with them early, just like cancer.
    Alright, i'm reading the article right now, and i will address this issue today, thanks.

  13. #9
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    I have read the article and the code, some of it is a little hard to understand because i'm not used to using parameters in methods yet. How can i use the methods in class Console in class Book?
    For example: at the start of the method run() in class Book, there is a method addUser(), i put:
    [borrower = Console.readString(don't know what to write here)]
    but this doesn't make it repeat if the user presses enter without typing his name, it prints the error but then continues with the rest of my code, i'm a bit confused :/
    Can you help me with a small example by substituting a part of my code with a method from Console so i can figure out the rest myself?

  14. #10
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    I played around with the Console methods, all of them work great, as intended, apart from the readString() methods. If i press enter without writing anything, it prints the error prompt but then simply continues to the next code :/ it's not really a big issue for me, the name of the user is not necessary, but why isn't it working correctly?

  15. #11
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Thumbs up Re: Simple Library Program / Need feedback.

    I just finished re-factoring the code into 6 different Classes, i can see the advantages now and i managed to use the Console class (it simplified lots of steps). I still have some minor bugs that i will try to fix today or tomorrow.
    I attached the files in a zip folder if you guys want to check it out. To be frank, i'm very happy with the re-factoring even if it's not exactly the correct way, it's much easier now to modify code without affecting other classes (in some cases at least).
    Tomorrow i will have a meeting with our lecturer and discuss the code, especially the static/private/final stuff, but for now the code is working to some degree and doesn't crash from input-mismatches, which is great.

    Thank you all

    library.zip

  16. #12
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Simple Library Program / Need feedback.

    EDIT:
    This is directed at Christopher

    Hmm, I was able to reproduce the problem with this:

     
    import java.util.Scanner;
    /**
     * This tests the Console's readString method if the user enters
     * nothing.
     * 
     * @author Timothy Moore
     */
    public class NullPointerExceptionTest
    {
      public static void main(String[] args)
      {
        Scanner in = new Scanner(System.in);
        Console.readString("Enter blank, then something", "Good work!");
      }
    }

    After a cursory inspection, you forgot to use a recursive call in that method, impressive nobody noticed until now

    public static final String readString(String prompt, String error) {
      String input = readLine(prompt);
      if ((input.length() == 0) || (input == null) || (input.equals("\n"))) {
       System.out.println("\n" + error);
      }
     
      return input;  
     }

    Simple fix is to change it to

    public static final String readString(String prompt, String error) {
      String input = readLine(prompt);
      if ((input.length() == 0) || (input == null) || (input.equals("\n"))) {
       System.out.println("\n" + error);
       return readString(prompt, error);
      }
     
      return input;  
     }
    Last edited by Tjstretch; March 19th, 2012 at 04:02 PM.

  17. The Following 2 Users Say Thank You to Tjstretch For This Useful Post:

    ChristopherLowe (March 20th, 2012), ziplague (March 20th, 2012)

  18. #13
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    @Tjstretch: Wow, cool, thank you for the fix

  19. #14
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Simple Library Program / Need feedback.

    @Tjstrech Excellent! Thanks for the bug fix. I will update the article with the fix.

    Quote Originally Posted by Tjstrech
    impressive nobody noticed until now
    No joke, this should never have fallen through my test cases. Oh well no ones perfect. In truth, the string related functions are seriously lacking in this utility. I had planned to write functions that only accept a list of correct inputs and inputs with length ranges but never really had the need for them so didn't bother.

    Anyway thanks again.
    Last edited by ChristopherLowe; March 20th, 2012 at 02:33 AM.

  20. #15
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Simple Library Program / Need feedback.

    @ziplague Yeah the new code is looking much better. You still need to look into the use of static but the structure is looking great.

    To use my console class to accept a menu choice you could do something like this:

    // Prompt the user for a number in the range 1..4
    int userInput = Console.readInteger("Enter you choice:", "Invalid menu choice. Try again", 1, 4);
    The first parameter is the prompt. The second is the error message. The third is the minimum value and the fourth the maximum.

    But let me warn you that your lecturer is not going to like you using someone else's code like this. If you were to remove my name from the comments two things would happen. Firstly, I would not be very happy. Secondly, your lecturer will recognize code that does not fit in with your coding style and accuse you of plagiarism. That's why I suggested you should look at how I handle user input and write your own method based of it. I wouldn't want you failing an assignment because of this...

  21. The Following User Says Thank You to ChristopherLowe For This Useful Post:

    ziplague (March 20th, 2012)

  22. #16
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    But let me warn you that your lecturer is not going to like you using someone else's code like this. If you were to remove my name from the comments two things would happen. Firstly, I would not be very happy. Secondly, your lecturer will recognize code that does not fit in with your coding style and accuse you of plagiarism. That's why I suggested you should look at how I handle user input and write your own method based of it. I wouldn't want you failing an assignment because of this...
    My lecturer told me that i can use someone else's code on three conditions:
    1- i must understand the code, how it works etc...
    2- it should constitute less than a third of my code, meaning that it shouldn't dominate my code etc...
    3- i should credit the original writer (you in this case ).

    So everyone will be happy
    Last edited by ziplague; March 20th, 2012 at 03:19 AM.

  23. #17
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Unexpected Error

    I updated my code and everything seems to be working fine with minor duplicates which i'm going to address tomorrow, but i keep getting this error:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(Unknown Source)
    at library.Library.borrowBook(Library.java:72)
    at library.Book.run(Book.java:93)
    at library.startLibrary.main(startLibrary.java:19)


    here is the borrowBook() method:

    	static void borrowBook(){
    		System.out.println("---------------------------------------------------------");
    		System.out.println("> Here are all the books registered in the library: ");
    		System.out.println("---------------------------------------------------------");		
    		displayBookList();
     
    		//register user's book choice.
    		//bookChoice = (Console.readInteger(Messages.enterBookIndexMessage, Messages.bookIndexNotInListMessage, 1, Library.bookList.size()))-1;
     
    		borrowLoop:
    		while(Menu.menuChoice == 3){
    			//Check if the book to be borrowed is available.
    			bookChoice = (Console.readInteger(Messages.enterBookIndexMessage, Messages.bookIndexNotInListMessage, 1, Library.bookList.size()))-1;
     
     
    //This is the line 72 that gives the above error: 
    			if ((bookList.get(bookChoice).status.equalsIgnoreCase(status1)) && (bookList.size() >= bookChoice)){
    				//Print the borrowed book information and change the book status to borrowed.
    				bookList.get(bookChoice).status = "Borrowed";
    				bookList.get(bookChoice).borrower = User.userName;
    				bookList.get(bookChoice).borrowDate = "Today.";
    				bookList.get(bookChoice).returnDate = "In two weeks.";				
     
    				System.out.printf("\n\n> You have chosen the following book:\n %s\n\n", bookList.get(bookChoice).displayBook());
    				System.out.println("\n\n> You have to return the book in two weeks!\n\n");
    				break borrowLoop;
     
    			}else if(bookList.get(bookChoice).status.equalsIgnoreCase(status2) && bookList.size() >= bookChoice){
    				System.out.println("\n\n<ERROR> The Book you are trying to borrow is unavailable!\n\n");
    				break borrowLoop;
     
    			}else if(bookChoice > bookList.size()-1){
    				System.out.println(Messages.noSuchBookMessage);
    				break borrowLoop;
    			}
    		}
    		Menu.displayMenu();
    	}

    This error is bugging me, i'm beginning to think that it's Eclipse that's buggy instead of my code :/
    The logic looks fine (at least i think so).

    I even noticed that sometimes Eclipse or the java compiler simply skips a readInteger statement without waiting for input from the user, is this a common issue?

    Anyway, i attached my new Class files in a zip folder, feel free to check it out. (Sorry for insufficient documentation/comments, i'm still trying to optimize the code to get rid of duplicate print outs and logic problems etc...)

    library.zip
    Last edited by ziplague; March 21st, 2012 at 03:23 AM.

  24. #18
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Unexpected Error

    I think that file you uploaded is not up to date. It does not contain a main method and when I put one in I could not replicate the error. Also I could not replicate the readInteger method skipping that you mentioned.

    I did however find a similar ArrayOutOfBounds exception in the deleteBook method. The cause is you are removing a book from the ArrayList and then trying to print the name of the book. You can't because it has been removed.

    Quote Originally Posted by ziplague
    This error is bugging me, i'm beginning to think that it's Eclipse that's buggy instead of my code :/
    The logic looks fine (at least i think so).
    No it is your code. Understand that eclipse is just a glorified text editor that sits on top of the java compiler. Although eclipse does have it's fair share of bugs it will not make a mistake compiling your code. And saying that it is javac's fault is a little like saying I crashed my car when I was drunk because there was something wrong with the road.

    Just one more point I wanted to bring up - do you think that your methods for hiring/deleting/returning books are in the right place. Think objects. What are the nouns and verbs associated with a book? You can read a book. A book has a title, an author, etc. What are the nouns and verbs associated with a library? You can hire a book, return a book, look at the catalog of books. A library has a name, an address, a collection of books. See what I am getting at?

  25. The Following User Says Thank You to ChristopherLowe For This Useful Post:

    ziplague (March 21st, 2012)

  26. #19
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Unexpected Error

    My bad, i uploaded the wrong version by mistake, here is the up to date version: library.zip

    About the right placement of the methods, you're right, i thought about that. I will move them to the book class since they deal with the book object, but moving them is the easy part , making sure they work properly is more important for me now. Although they kinda are a part of the library function as well, they act on books but they are things you do in the library, for example i don't borrow books at home, so yeah, it's not really that trivial for me where they are as long as they work.

    By the way, i talked to the instructor about the project and the static stuff. His answer was kinda predictable, he said that i have already jumped outside of the scope of this course, our assignment was actually to have 5 books max (non dynamic library) and that he won't spend time on advanced topics. I was kinda disappointed, but i understand his opinion as well .

    About the error: I am not removing the book, i'm simply changing it's status to borrowed, and the print statement is before that, so why is it telling me that it is out of bounds since i can clearly see that it isn't?
    I don't really get it.

  27. #20
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    By the way, about the error that i'm getting: it only occurs with certain indexes, usually with the ones at the end of the array (last index), if i add 3 books, index 2 and 1 work fine, which contradicts with your answer
    The cause is you are removing a book from the ArrayList and then trying to print the name of the book. You can't because it has been removed.

  28. #21
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Simple Library Program / Need feedback.

    I fixed the out of bounds exception.

  29. #22
    Member ziplague's Avatar
    Join Date
    Nov 2011
    Location
    Sweden
    Posts
    33
    My Mood
    Cheerful
    Thanks
    9
    Thanked 1 Time in 1 Post

    Talking Re: Simple Library Program / Need feedback.

    This is the end of this thread, due to deadlines and exams coming soon, i have to submit my Java project for grading.
    I want to thank everyone who helped me improve my code and solve problems you've been very helpful.

    I am planning to add more functionality to the code:
    - Output and input to file for storing the data after exiting the library.
    - GUI for better user interface and standalone capability.
    - Better re-factoring for easier expansion later on.

    So i will open another thread when i start coding the extra functionality.
    After looking at some of my teammates' codes, i predict that i will get the top grade in my class nobody else did a dynamic library.
    Once again, thank you all, it's been a pleasure and a wonderful experience learning from you guys

    LibraryJavaApplicationProject.zip

  30. #23
    Junior Member
    Join Date
    May 2014
    Location
    KOTA KINABALU, SABAH
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Simple Library Program / Need feedback.

    hi ziplague... im also have same assignment with you.. my assignment tittle is Textbook loan... i need your help and to teach me what suppose i do.. and can i see your coding for my reseach to do my assigment.. i hope you can help me~

Similar Threads

  1. My New Website | Feedback Please!
    By OA-OD-JD1 in forum Totally Off Topic
    Replies: 3
    Last Post: July 16th, 2012, 01:30 AM
  2. Feedback Wanted for My Website
    By KevinWorkman in forum The Cafe
    Replies: 17
    Last Post: October 6th, 2011, 06:57 AM
  3. please help with simple program!!!
    By jokneez in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 14th, 2011, 10:42 AM
  4. urgent simple help for a very simple program
    By albukhari87 in forum Java Applets
    Replies: 4
    Last Post: June 5th, 2010, 03:43 PM
  5. simple program
    By Memb in forum Paid Java Projects
    Replies: 0
    Last Post: March 17th, 2010, 01:47 PM

Tags for this Thread