Constructor with Field from another class is undefined? - java

I'm tasked by a newbie Java tutorial to do the below
In the user class:
Create a method called readBook(Book book)
readBook should print, "<User> read <title>"
In the BookRunner
For each book, create an author.
Separately, create another user and call the readBook method on that user, passing in one of the created books
The below is my code:
public class Ex1_BookRunner {
public static void main(String[] args) {
Book firstBook = new Book("One Piece", "Oda-Sensei", 100, 123456);
Book secondBook = new Book("Life of Megan Fox", "Micheal Bay", 200, 928765);
}
}
public class User {
public String name;
public int age;
public String location;
public Book title;
public String toString() {
String description1 = "Name:" + name + " Age:"+ age + " Location:" + location;
return description1;
}
public void readBook(Book book) {
System.out.println(name + " read " + title.title);
}
}
public class Book {
public String title;
public User author;
public int numPages;
public int isbn;
public Book(String title, User author, int numPages, int isbn) {
this.title = title;
this.author = author;
this.numPages = numPages;
this.isbn = isbn;
}
public String toString() {
String description = "Title:" + title + "Author"+ author.name + "Num. of pages" + numPages + "ISBN" + isbn;
return description;
}
}
I'm having problems even understanding what the question wants me to do. I've got the below questions
What does the question mean by getting me to print <User> read <title> with the readBook method? Did I interpret the question correctly with the way I set up the readBook method?
What should be the correct code in the method?
I have problems getting the author created, as I get the error The constructor Book(String, String, int, int) is undefined and the Eclipse IDE wants me to change the constructor in Book from (String, User, int, int) to (String, String, int, int). Experiments with User."Oda-Sensei", "Oda-Sensei".name, "Oda-Sensei.User" all give me the notice that the variable I'm introducing cannot be resolved.

From the questioning, it sounds like authors are users. Your constructor calls in the main method are passing in strings, hence your error about the constructor. If authors are users, then you should change your calls from:
public static void main(String[] args) {
Book firstBook = new Book("One Piece", "Oda-Sensei", 100, 123456);
Book secondBook = new Book("Life of Megan Fox", "Micheal Bay", 200, 928765);
}
to
public static void main(String[] args) {
User odaSensei = new User();
odaSensei.name = "Oda-Sensei";
User michaelBay = new User();
michaelBay.name = "Michael Bay";
Book firstBook = new Book("One Piece", odaSensei, 100, 123456);
Book secondBook = new Book("Life of Megan Fox", michaelBay, 200, 928765);
}
Be sure to set the other variables of the authors The other option is to change the type of authors to String, in which case the main method will not have the change.
I'd also recommend adding a constructor for Users, so that you can just initialize all of the variables from the new call.
The second part "Separately, create another user and call the readBook method on that user, passing in one of the created books"
Is telling you to create a brand new user, e.g. bob
User bobUser = new User();
bobUser.name="Bob";
and then take this new user and have him read one of the books:
bobUser.readBook(firstBook);
The goal is to get the read book to print out:
Bob read One Piece
To do this, you'll need to change the readBook method from:
public void readBook(Book book) {
System.out.println(name + " read " + title.title);
}
to:
public void readBook(Book book) {
System.out.println(name + " read " + book.title);
}

Related

search an array in java and print the output

In this java program I am trying to search if an ISBN number exists in the "Book" type array or not. But when I try to implement the method and display the output, I am getting an error which says " The method searchBook(Book, String) is undefined for the type Book". The <-- HERE comment shows where the error pops up. I do not understand how to rectify this error and any help will be appreciated. Thank you.
The driver class is : QuizMain
public class User {
int ID;
String name;
String email;
int age;
String isbn;
void searchBook(Book[] b, String isbn) {
for (int i =0;i<6;i++) {
if (b[i].ISBN == isbn) {
System.out.println(b[i].title);
} else {
System.out.println("ISBN Not Found");
}
}
}
}
public class Book {
String title;
String author;
String ISBN;
float rating;
int noOfDays;
void displayBookDetails() {
System.out.println("Title\tAuthor\tISBN\tRating"+this.title +this.author + this.ISBN +this.rating);
}
// book constructor
public Book(String title, String author, String ISBN, float rating) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.rating = rating;
}
}
public class QuizMain {
public static void main(String[] args) {
Book[] arr = new Book[6];
arr[0] = new Book("Vincent la la ","king","2194-5357",6.5f);
arr[1] = new Book("A man of wisdom","henry","2193-4567",3.2f);
arr[2] = new Book("Apple Garden","timorthy","2104-3080",1.2f);
arr[3] = new Book("Sherlock","Arthur","2165-0932",5.5f);
arr[4] = new Book("Hello John","Tarnia","2134-2342",1.5f);
arr[5] = new Book("Tarzan","Martin","2111-0564",4.2f);
for(int i =0;i<arr.length;i++) {
arr[i].searchBook(arr[i], "2165-0932"); // <-- HERE
}
arr.searchBook(arr[5], "2165-0932"); // <-- HERE
}
}
In the User class the searchBook(Book[] b, String isbn) method accepts an array of Book and a String isbn value.
But while calling this method you are passing only one Book object instead of array of Book.
Move the searchBook implementation to QuizMain class and call this by passing array of Book as shown below for a workaround .
searchBook(arr, "2165-0932");
May be you need to concentrate on designing the class and its behavior.
There are two problems in your code. First one your searchBook function expecting Book type array and string but you are passing it one Book instant i.e arr[i] with string and secondly you have define the searchBook() function in User class and using it with object of Book class. Move your function to Book class. Even you don't need that function in any of Book or User class you can simply define static function searchBook(Book[] books, String isbn) inside your QuizMain class and call it like
searchBook(arr,"8344-3452")

Loop for ArrayList printing out null

I'm new to Java so sorry for all the mistakes!
Im creating a Library program consisting of 4 classes: Library, Book, BookInterface & Patron.
In the Book class I have a method that prints out all the books in the library and their status' (in or out). Instead I keep getting something like this:
Great Gatsby: null
Withering Heights: null
Does it have something to do with the setStatus() method?
Every time a user adds a new book, it creates a new Book instance and then I do setStatus("IN"). So how come it is not saving and instead printing out null?
Thank you very much for the help!!
Book class:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Book implements BookInterface
{
Scanner input = new Scanner(System.in);
static ArrayList <String> UserList = new ArrayList<String>();
static ArrayList <String> BookList = new ArrayList <String> (); //display just titles// use when checking out books
static ArrayList <String> OrigBookList = new ArrayList <String> (); //keep track of all titles ever entered
public String title;
public String author;
public String book;
public boolean checkIn;
private String status;
private String borrower;
public Book(String t, String a)
{
title = t;
author = a;
}
//constructor create new book
public Book(String newTitle)
{
title = newTitle;
}
public String toString()
{
return title + " " + 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;
}
public String getStatus(String book)
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public void setBorrower(String borrower)
{
this.borrower = borrower;
}
public String getBorrower(String checkPatron)
{
return borrower;
}
public String getBook(String checkPatron)
{
return book;
}
public void setBook(String bookCheckOut)
{
this.book = bookCheckOut;
}
public void addBook()
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.print("Enter book title: ");
String title1 = inputread.nextLine();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = inputread.next();
Book fullBook = new Book(title1, author1); //create constructor w/ title & author
Book book1 = new Book(title1); //constructor w/ just title to be used to display all books
OrigBookList.add(title1);
book1.setStatus("IN");
System.out.println("-----------------------------------------------");
System.out.println("-----" + title1 + " is now in the library!-----");
System.out.println("-----------------------------------------------");
}
public void editBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original book title: ");
String origTitle = inputread.nextLine();
System.out.println("Enter edited book title: ");
String editedTitle = inputread.nextLine();
Collections.replaceAll(Book.UserList, origTitle, editedTitle);
System.out.println("------------------------------------------------------");
System.out.println(origTitle + " has been changed to " + editedTitle + "!");
System.out.println("------------------------------------------------------");
}
public void libraryInventory()
{
System.out.println("------------------ Library Inventory: ---------------");
for(int i =0; i<= OrigBookList.size()-1; i++)
{
//Book Title: checked in/out
System.out.println(OrigBookList.get(i) + ":" + getStatus(OrigBookList.get(i)));
}
System.out.println("-----------------------------------------------------");
}
}
getStatus(OrigBookList.get(i)) ignores the parameter you pass to it and just returns the status of the Book for which you called the libraryInventory method. Obviously, that Book instance doesn't have the status field initialized, but even if it did, it will give you the status of just one Book.
Instead of having a static list of book titles (static ArrayList <String>), perhaps you should maintain a list of the books themselves (static ArrayList <Book>), or even better, put that list in a separate class (you can call it Library).
Methods such as libraryInventory shouldn't be in the Book class (and if you insist on keeping them in the Book class, make them static, since they don't refer to a single Book instance).
Your whole program seems to be running inside an instance of the class Book. In it, you are making and discarding new instances of Book, called fullBook and book1, and for fullBook you set its status. When you call getStatus on the main Book in your program, it just returns its own status, which was never set to anything.
If you want to save a sequence of instances of Book, you need to put the instances somewhere, not just instantiate them and then add the title to a list.

Calling class methods from another class

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.

Using an "add" method to add objects to an ArrayList from a separate class

I'm relatively new to Programming in general and I've been grafting over this piece of work for hours and haven't got any further. I've trawled through the depths of the internet and I cannot find an answer similar to what I am looking for. Here in the Spec:
A) Create two files FictionBook.java and Library.java.
Define a FictionBook class that represents a single book. The book will have a
title, an author, an availability field (1=available, 0=on loan). You should define
accessor methods to borrow and return the book and read the title and author
and an accessor method to return the availability.
Additionally, define a Library class that contains up to 200 books. The library
should model containing books with an ArrayList. The Library
class should contain a method to add a book to the library, delete a book from
the library and borrow and return books.
B) Create a Librarian.java file and modify the Library.java file.
Write code to sort the messages in the Library so that all the books are in
alphabetical order by Author’s name. Create a Librarian class with only a main
method, so you can simulate the processing of books in the library. Generate
10 new FictionBooks and add them to a Library using the addBook method.
Your Library should place the message in the correct place in the library
depending on the name of the author.
I think I have completed the first part, although I could be wrong. It is the second part which I am complete stuck on. Here are my three classes
public class FictionBook {
private String title, author;
private int availability;
public FictionBook(String title, String author, int availability){
super();
this.title = title;
this.author = author;
this.availability = availability;
}
public FictionBook() {
this.availability = 1;
}
public void borrowBook1() {
setAvailability(0);
}
public void returnBook1() {
setAvailability(1);
}
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;
}
public int getAvailability() {
return availability;
}
public void setAvailability(int availability) {
if(availability != 1 || availability != 0) {
System.err.println("Enter 1 for available. Enter 2 for on loan.");
throw new IndexOutOfBoundsException();
} else {
this.availability = availability;
}
}
}
import java.util.ArrayList;
public class Library {
static ArrayList<FictionBook> BookList = new ArrayList<FictionBook>(200);
public static void addBook(FictionBook String){
BookList.add(String);
System.out.println("Book Successfully Added To Library Database.");
System.out.println(BookList);
}
public void deleteBook(){
BookList.remove(index);
}
public void borrowBook(){
BookList.get(index).FictionBook.borrowBook1();
}
public void returnBook(){
BookList.get(index).FictionBook.returnBook1();
}
}
public class Librarian {
public static void main(String args[]){
FictionBook newBook1 = new FictionBook("USB Man", "Bob", 1);
FictionBook newBook2 = new FictionBook("Bin Boys", "Chris", 1);
FictionBook newBook3 = new FictionBook("Dinosaur", "Joe", 1);
FictionBook newBook4 = new FictionBook("Pigasaurus", "Tom", 1);
FictionBook newBook5 = new FictionBook("Cat Attack", "Calvin", 1);
FictionBook newBook6 = new FictionBook("Shark Man", "Alfie", 1);
FictionBook newBook7 = new FictionBook("Burnt Face Man", "Colin", 1);
FictionBook newBook8 = new FictionBook("Egg Life", "Darwin", 1);
FictionBook newBook9 = new FictionBook("Pizza King", "Pringle", 1);
FictionBook newBook10 = new FictionBook("BillyBonka", "Randy", 1);
Library.addBook();
}
}
I am just wondering how I actually use the addBook(); method in my Library class to add the objects defined in the Librarian class to the ArrayList in my Library class? I've been messing around with the code a lot so there may be a lot of mistakes, apologies in advance. Any help would be super.
Thank you in advance for your time!
Look at where you defined the addBook method:
public static void addBook(FictionBook String)
this means that whenever you want to call addBook, you MUST include the name of the book (the name of the object of the FictionBook, not the literal title. And you must do this for each book since you're only doing them one at a time.
so try this
FictionBook newBook1 = new FictionBook("USB Man", "Bob", 1);
Library.addBook(newBook1);
FictionBook newBook2 = new FictionBook("Bin Boys", "Chris", 1);
Library.addBook(newBook2);
etc. etc. for each book you define
also, like Compass said, naming a local variable "String" is not a good idea at all. I would rename it something like book because it's technically not the name of the book, it's the name of the object.

Console Display for System.out.println(refVar name)

How can System.out.println(refVar name) give the output shown by this example's website? I understand why "Simcard object constructed" gets displayed, but why do the remaining fields get displayed in that specific order: "New Sim card constructed for nokia 1100."
My understanding is that fields can't just be outputted by calling a reference name.
(http://www.hubberspot.com/2012/07/how-composition-has-relationship-works.html)
class SimCard {
private String cardNumber;
public SimCard(){
System.out.println("SimCard Object Constructed");
cardNumber = "New SimCard Constructed";
}
#Override
public String toString() {
return cardNumber;
}
}
public class Mobile {
private SimCard sim = new SimCard();
private String mobile = "Nokia";
private int model = 1100;
#Override
public String toString() {
return sim + " for " + mobile + " " + model;
}
public static void main(String[] args) {
Mobile mob = new Mobile();
System.out.println(mob);
}
}
The mobile/model are getting created when you create the new instance
Mobile mob = new Mobile()
They get set to their defaults as specified in the class.
Then when you output the class the overidden String method is called which returns the output to main and it is printed.

Categories

Resources