I have created a class for a book with various field. I have then created a an array class for the library to store the book details. However I am not sure how to link them. I am looking to ultimately be able to search my array for all books with the same author surname for example. Should I somehow be calling methods from the book code to the library code?
This is my object class
public class Bookrecord
{
private int idnumber;
private String author;
private String title;
private String fiction;
public Bookrecord( int newidnumber, String newauthorname, String newtitlename, String newfictionname)
{
idnumber = newidnumber;
author = newauthorname;
title = newtitlename;
fiction = newfictionname;
}
public int getidnumber()
{
return idnumber;
}
public String getauthorname()
{
return author;
}
public String getfictianname()
{
return fiction;
}
public String gettitlename()
{
return title;
}
public void setidnumber(int insertidnumber)
{
idnumber = insertidnumber;
}
public void setauthor(String insertauthorname)
{
author = insertauthorname;
}
public void setfictian(String insertfictionname)
{
fiction = insertfictionname;
}
public void settitle(String inserttitlename)
{
title = inserttitlename;
}
public void printBookrecord()
{
System.out.println("The idNumber is " + idnumber + " The authorname is " + author + " The fictionname is " + fiction + " The titlename is " + title);
}
}
This is my array class
import java.util.ArrayList;
public class Libraryclass
{
// instance variables - replace the example below with your own
private ArrayList<String> member;
private ArrayList<String> bookrecord;
private ArrayList<String> libraryloan;
/**
* Constructor for objects of class Loan
*/
public Libraryclass()
{
// initialise instance variables
member = new ArrayList<String>();
bookrecord = new ArrayList<String>();
libraryloan = new ArrayList<String>();
}
public void addMember(String newMember)
{
member.add(newMember);
}
public void bookrecord(String newrecord)
{
bookrecord.add(newrecord);
}
public void libraryloan(String newloan)
{
libraryloan.add(newloan);
}
}
This reminds of an assignment for my first object oriented course. I get the feeling you also just started development and need some tips to get started.
Keep in mind we won't spoonfeed the answer to you since it is frowned upon to use stackoverflow to get complete answers to college assignments.
Your library or (arrayclass) should store an Array of BookRecord objects. Currently your arraylists hold String Objects. You should re-read what objects and classes are, to better understand the underlying concepts. You want your Library to hold an arraylist of bookrecords.
FYI: An Arraylists is a class available in java that allows the addition and removal of elements. It has some advantage related to arrays but also has some cons.
Your library object will use 'for loops' or 'iterators' to go through your arraylist of records. In order to implement features such as search for book you need to learn how to iterate over elements in an arraylist to search for strings. Google is your friend here. Here is an example what someone in your position should search for:
-searching through an arraylist, java
-iterating over arraylist, java
-how to use indexof java stack overflow
Finally, it makes more sense to call methods of the BookRecords from the Libraryclass. A bookRecord has one and only one Library. A library has many books. Hence, the library will hold references (contain) the books and will call getters and setters on the books.
Related
I have 3 classes, Book, ChildrensBook and Library. ChildrensBook extends the Book class.
ChildrensBook contains the additional variable recommendedAge.
Library contains an array that can include both Book and ChildrensBook objects.
In the class Library I have to create the method int forChildren(int n) that returns how many childrensBook of age less or equal to n are there in array Library.
the problem is that in the library array there are both Books and ChildrensBooks, so I can't access the recommendedAge variable, because it is only inside a children's book. how can I do?
public class Library {
private ArrayList <Book> collection;
public Library(ArrayList <Book> c){
collection=c;
}
public int forChildren(int n) {
int count=0;
for(int i=0;i<collection.size();i++) {
if((collection.get(i).getRecommendedAge)<=n) {
count++;
}
}
return count;
}
public class Book {
private String title;
private String author;
public Book(String title, String author){
this.title=title;
this.author=author;
}
}
public class ChildrensBook extends Book {
private int recommendedAge;
public ChildrensBook(String title,String author,int recommendedAge){
super(title,author);
this.recommendedAge=recommendedAge;
}
public int getRecommendedAge() {
return recommendedAge;
}
}
Basically I see three possible approaches:
Pull the knowledge about recommended ages up to the Book class so that every book has a recommended age although you then need to decide which recommended age a non children's book has.
Decide on iterating over the books if a Book is a children's book or not - this can be achieved using Java's instanceof operator although this is not particularly object oriented.
Add a method similar to isValidForAge for books deciding if a book is valid for a certain given ages or not which every children's book answers based on the recommended age and every non children's book needs to answer based on other criteria.
This is improper class design.
You mixed a concern of books classification (children, adult, science-fiction, humor) which is more like a category or "tag" and the particular behavior (which is suitability for the audience).
You may decide to make a Book class abstract and inherit a concrete AdultBook class from it.
As already mentioned in other answer, you could have an adult book which is still suitable for children. Let's say a biography or an encyclopedia.
Which means, you may want to exercise getRecommendedAge() on every book in your collection.
You can use instanceof operator to check the type of the object. Try the below code:
public class Library {
private ArrayList<Book> collection;
public Library(ArrayList<Book> c) {
collection = c;
}
public int forChildren(int n) {
int count = 0;
for (int i = 0; i < collection.size(); i++) {
if (collection.get(i) instanceof ChildrensBook) {
if (((ChildrensBook) collection.get(i)).getRecommendedAge() <= n) {
count++;
}
}
}
return count;
}
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
public class ChildrensBook extends Book {
private int recommendedAge;
public ChildrensBook(String title, String author, int recommendedAge) {
super(title, author);
this.recommendedAge = recommendedAge;
}
public int getRecommendedAge() {
return recommendedAge;
}
}
I have two classes in java: Movie and Book (it's a simplified example):
Book can have author:
public class Book {
public String author;
public Book(String a) {
this.author = a;
}
public String getAuthor(){
return author;
}
}
And Movie can have title:
public class Movie {
public String title;
public Movie(String t) {
this.title = t;
}
public String getAuthor(){
return title;
}
}
I'm trying to put all objects in a list like this:
ArrayList myList = new ArrayList();
Book book = new Book("William");
Movie movie = new Movie("Titanic");
myList.add(book);
myList.add(movie);
And afterwards I want to count how many books written by John do I have (or any other specific titles). However I can't apply getAuthor() or getTitle() method since java doesn't know what type of object it is
int counter = 0;
for (int i =0;i<myList.size();i++){
if (myList.get(i).getAuthor().equals("John") ){
counter +=1;
}
I would be able to use if clause, check every time for an object type, and apply different methods for different objects, but this is not viable, since in real-life case I have 20+ classes and it would make code very long and maintainable.
Can someone suggest a solution for this? Thanks in advance!
create an interface
public interface HasAuthor {
String getAuthor();
}
implement this interface in both your classes and use this:
List<HasAuthor> list = new ArrayList<>();
list.add(new Book());
list.add(new Movie());
long count = list.stream().filter(smth -> "John".equals(smth.getAuthor())).count();
You cannot be using ArrayList myList = new ArrayList(); in 2017. The world has moved on from that archaic and error-prone style of programming. Generics were added to the Java programming language in 2004, and since then, any attempt to use a generic class without a generic type argument issues a warning. Which brings me to the next issue:
You cannot be ignoring warnings in 2017. Actually, there was never a good time to be ignoring warnings. Your IDE ought to be issuing warnings when you try to do ArrayList myList = new ArrayList(); heed them.
So, bottom line is, you should not be putting books and movies in the same collection. If you have a book class that has an author, and a movie class that has a director, (I will ignore your example of movies having a title and returning that as "author", because it is nonsensical,) then you can have either an interface or an abstract base class called, say, Item, with a String getAuthor() method, which is implemented (overridden) in both Book and Movie.
Then, your myList will be an ArrayList<Item>, and since Item has a getAuthor() method, you will be able to do myList.get( 0 ).getAuthor() and it will work without having to know whether it is a book or a movie.
First, myList.get(i).getAuthor() == "John" won't work since strings need to be compared via equals() (look up tutorials on why).
Second, you need to know the type of your objects and cast accordingly in order to call a method (you could do without the cast using reflection but please don't try that at home). Thus when iterating over your list you need to check:
for (Object o : myList ) {
if (o instanceof Book && ((Book)o).getAuthor().equals("John") ){
counter +=1;
}
}
However, if you want one list to contain all books and movies you'd better provide a common interface or superclass:
//Make it abstract to not allow instances of this class directly
abstract class PieceOfArt {
private String creator;
public String getCreator() {
return creator;
}
}
class Book extends PieceOfArt {
//Access the creator as the author
//note that I do this just for demonstration purposes, just using getCreator() would be perfectly fine
public String getAuthor() {
return getCreator();
}
}
class Movie extends PieceOfArt {
//Access the creator as the director
//note that I do this just for demonstration purposes, just using getCreator() would be perfectly fine
public String getDirector() {
return getCreator();
}
}
List<PieceOfArt> myList = ...;
for( PieceOfArt p : myList ) {
if( p.getCreator().equals("John") {
...
}
}
Putting objects of different, unrelated types, such as Book and Movie, which don't have a common superclass (besides java.lang.Object) is bad practice.
You could define a common abstract superclass for these types, and then create a List of that type. For example:
public abstract class Product {
private String title;
private String author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
class Book extends Product {
}
class Movie extends Product {
}
Create a List<Product> and work with that:
List<Product> products = new ArrayList<>();
Book book = new Book();
book.setTitle("Cooking");
book.setAuthor("Bob the Cook");
products.add(book);
Movie movie = new Movie();
movie.setTitle("Romance at sea");
movie.setAuthor("John");
products.add(movie);
int count = 0;
for (Product product : products) {
if (product.getAuthor().equals("John")) {
count++;
}
}
NOTE: Do not make the getAuthor method actually return the title in case of a Movie, that would make your program really confusing.
When i try to compile an aggregation program , i receive an error saying "class,interface,enum expected". Here is my code. please help me solve this issue.
class employee
{
private String name;
private String address;
private float salary;
public employee(String na, String add,float sal)
{
name = na;
address = add;
salary = sal;
}
public void showEmpDetails()
{
System.out.println("Name " + name);
System.out.println("Address " + address);
System.out.println("Salary " + salary );
System.out.println();
}
}
import java.util.vector;
class company
{
private String comname;
private vector vt;
public company(String na)
{
comname = na;
vt = new vector();
}
public void addEmployee(employee e)
{
vt.addElement(e);
}
public void showComDetails()
{
System.out.println("Company Name " + comname);
int x = vt.size();
int y = 0;
while(y<x)
{
object e = vt.elementAt(y);
e.showEmpDetails();
y++;
}
}
}
public class demo
{
public static void main(String[] args)
{
employee e1 = new employee("Ashan","Kandy",2000.0f);
employee e2 = new employee("Steve","California",2500.0f);
employee e3 = new employee("Elon","South Africa",2500.0f);
company c1 = new company("Apple");
c1.addEmployee(e1);
c1.addEmployee(e2);
c1.addEmployee(e3);
c1.showComDetails();
}
}
Note:- i receive only one error. and also can anybody tell me why can't i have more than one public class in java.
Well, your code has more than one error actually. The reason for your specific error is that import should be at beginning of the file, not in the middle.
And my understanding of why only one public class is allowed for each file is:
It makes things clearer.
By reading the class name and document to this class, you could quickly know what the whole file is used for. If we allow multiple public classes in one file, like C++, then we have to jump inside of the file to understand it.
Notice Java is a strong object-oriented language, i.e. everything in Java is Object. So when importing, you are importing a file. It would be more complicated if one file contains multiple public classes.
It simplify testing.
Each public class could have a main function. And you could run any main function of a file Demo.java simply by java Demo. This is really nice, so that you could write test code, or example of usage in main function to show other contributor how this class should be used.
There have to be other more in-depth reason for single public class in Java. But these are my perspective.
OK so I have the following Object class:
public class IntoleranceFood implements Comparable<IntoleranceFood>{
private int scoreInt;
public String foodName;
public IntoleranceFood(String food, int score) {
super();
this.foodName = food;
this.scoreInt = score;
}
//getters and setters
public String getFood() {
return foodName;
}
public void setFood(String food) {
this.foodName = food;
}
public int getScore() {
return scoreInt;
}
public void setScore(int score) {
this.scoreInt = score;
}
#Override
public String toString() {
return "Intolerance Food [Name=" + foodName + ", Score=" + scoreInt + "]";
}
#Override
public int compareTo(IntoleranceFood arg0) {
return toString().compareTo(arg0.toString());
}
}
And then in my Activity I have created an array for these objects to go into, and filled up the array with "IntoleranceFood" Objects:
int numFoodItemTypes = db.intoleranceFoodItemTypesTotal();
IntoleranceFood[] foodArray = new IntoleranceFood[numFoodItemTypes];
Cursor cAllFoodTypes = db.intoleranceFoodTypesList();
int foodItem = 0;
do{
foodArray[foodItem] = new IntoleranceFood(cAllFoodTypes.getString(0), 0);
foodItem++;
}while(cAllFoodTypes.moveToNext());
I managed to sort the array by implementing Comparable and the compareTo method in my Object class:
Arrays.sort(foodArray);
But I want to then search the array using binary search, and look for the position in the array where a certain Object with a specific food name (String) resides. But I dont know how to get the following code working, and specifically in terms of:
-binarySearch(Object[] array, Object value)
I don't know what to put in "Object value" so this:
Arrays.binarySearch(foodArray, "Cereal");
Is clearly wrong! But I'm not sure how to search the Object array for an Object containing the String food name "Cereal".
Thanks.
Yes so after the very useful reply below, I realsied what I need to be doing is:
IntoleranceFood searchOb = new IntoleranceFood("Cereal",0);
int searchIndex = Arrays.binarySearch(foodArray, searchOb);
And that works!
In my opinion your mistake is
Arrays.binarySearch(foodArray, "Cereal");
because "Cereal" is not the Object you are looking for and your array doesnt contain this object. The second parameter should be an instance of the IntoleranceFood class and "Cereal" is just a property of that class.
For your problem i would use a HashMap or another Map who fits your problem best!
Maybe this article will help you : How to sort a HashMap in Java
I have asked this question before and followed the feedback as best as I could but I am still having one problem with storing the info that the user enters into the array.
Here is the first attempt:
OOP Java: Creating a stock inventory program
So I need to have in total three classes(That's required). The Stock, stock inventory and then the user interface. The purpose of this program is to ask the user to input the company's name, stock rating, price and the number of shares. Of course, I then have to do other things. I think I am okay with the rest, the problem is the stockInterface, the last bit of code that I post below.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
public class StockInterface() {
private static StockInventory stockPortfolio;
public static void main (String [] args){
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
This piece of code doesn't work.
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares)
Can somebody please show me the proper way to store the info into the array? Thank you very much.
Lots of compile errors...
You have defined stockRating as a String but yet return it as an int:
public int getStockRating() {
return stockRating;
}
The same is true for price.
You have extra parenthesis here:
public class StockInterface() {
^
Also in StockInventory, there are multiple statements in the class block They belong in a method.
console is not instantiated.
stockPortfolio is assigned as an array entry, yet it is a single object, and assigned to the Stock which is not a matching type.
So you've declared the stockPortfolio as an instance of StockInventory. StockInventory is a class not an array, so you can't use stockPortfolio [0] = ... because stockPortfolio is an instance of the class. You have a private member in StockInventory that is an array of Stock class instances. What you need is an accessor method to be able to manipulate it. So change StockInventory as follows:
public class StockInvetory {
/*
All the code you have now ...
*/
public Stock [] getStocks(){
return stocks;
}
public setStocks(Stock [] value){
//maybe some checking here ...
stocks = value;
}
}
Now just a slight change in using the class. You need to use the accessor methods as follows:
public class StockInterface {
/*
What you have just the following line changes ...
*/
stockPortfolio.getStocks()[0] = new Stock(stockName, stockRatings, stockPrice, numberShares);
}
I am assuming you are happy with the way you are initializing the array and that you have decided arrays are better than more dynamic data structures in collections for your specific project. If this is not true have a look at Java Collections they may bring you more joy.