java - Use 2 methods 1. Check if object exists 2. Add object -
i wondering how go create 2 methods, 1. checking, if object exists within array (based on 1 of parameters). 2. secondly add method allows user / me add objects array when previous (1st method) returns false.
here try:
public class book { string name; int isbn; public book(string e, int inr) throws libraryexception{ if(e.equals("")){ throw new libraryexception("blank / empty name not allowed!"); } else if(inr < 1 || inr > 9000){ throw new libraryexception("the isbn number outside allowed range (1 - 9000)! "); } setname(e); setisbn(inr); } public boolean equals(object obj){ if(obj instanceof book){ isbn = (isbn)obj; return true; } return false; } public string getname() { if(name == null || name == ""){ system.out.print("does not exist!"); } return name; } public void setname(string name) { this.name = name; } public int getisbn() { if(isbn < 0){ system.out.print("isbn (libri) exception added!"); } return isbn; } public void setisbn(int isbn) { this.isbn = isbn; } }
.
public class library { string name; book[] books; int nrbooks = 0; public library(string name, int nrbooks) throws libraryexception { if(name.equals("")){ throw new libraryexception("blank names not allowed"); } if(nrbooks < 500){ throw new libraryexception("the number of books needs greater 500!"); } this.name = name; this.nrbooks = nrbooks; this.books = new book[nrbooks]; } public void addbook(book book) throws libraryexception { if(indexof(book) == -1){ if(nrbooks < books.length) books[nrbooks++] = book; } } private int indexof(book book)throws libraryexception { if(nrbooks < book[].length){ } return -1; } public static void main(string[]args) throws libraryexception{ library b = new library("sami frasheri", 700); b.addbook(new book("paul colhen - alchemist", 1)); b.addbook(new book("paul colhen - winners stand alone", 2)); b.addbook(new book("paul colhen - river piedra sat , cried", 3)); system.out.print(b); } }
tried arraylist in java?.
they able solve of problems facing. have @ contains
, add
.
please note, must override hashcode
, equals
method of book object work effectively.
Comments
Post a Comment