I am making a simple program that sets the title and name of an object: book1. Eventually, the goal is to have several books under the Patron class that will use the Book class to assign values. However, I am running into difficulty simply getting the Patron class to acknowledge the Book class methods.
Basic Tester/Main method:
import java.util.Scanner;
public class ProjectFiveSix {
public static void main(String[] args) {
String title = "Bob";
String name = "Hugo"; // name of patron (class assigning book)
String author = "Rodrigo";
Patron patronOne = new Patron();
patronOne.setName(name);
Patron Class :
public class Patron {
private String name;
private Book book1;
private Book book2;
private Book book3;
public Patron(){
name = "";
book1 = null;
book2 = null;
book3 = null;
}
public String setName(String name){
return name;
}
public String borrowBook(String book1, String titleFinal, String authorFinal, String title, String author){
if (book1 == null){
book1.setTitle(titleFinal); //**
book1.setAuthor(authorFinal); //***
}
}
}
Book Class:
public class Book {
private String titleFinal;
private String authorFinal;
public Book(){
titleFinal = "";
authorFinal = "";
}
public String setTitle(String title){
titleFinal = title;
return titleFinal;
}
public String setAuthor(String author){
authorFinal = author;
return authorFinal;
}
}
Here I am getting "Cannot find Symbol" on both lines book1.settitle and book1.setauthor. The book has been instantiated and I cannot figure out the problem.
Thanks in advance!
You declared your parameter book1 (a String) as the same name as your instance variable book1 (a Book). To reference the instance variable, either name the parameter a different variable name, or use this. to specify the instance variable:
this.book1.setTitle(titleFinal); //**
this.book1.setAuthor(authorFinal); //***
Either way, you'll need to create an actual Book instance, or else your instance variable book1 will remain null and you'll get a NullPointerException.
Related
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")
So I have created a simple class in Java like this:
public class Book {
private String author;
private String title;
public Book (String author, String title) {
this.author = author;
this.title = title;
}
}
public void checkInfo
Is there a way to parse a string (property) in order to get Book properties like this, instead of doing bookA.title ?
Book bookA = new Book("George Orwell","Animal Farm")
String property = "title";
System.out.print(bookA.property);
Thanks in adance!
If you really want to access many properties as String, I suggest you using a Map<String, String> like this :
public class Book
{
private Map<String, String> properties = new HashMap();
public void setProperty(String name, String value)
{
properties.set(name,string);
}
public String getProperty(String name)
{
return properties.get(name);
}
}
Now you can use like this :
Book book = new Book();
book.setProperty("title","Animal Farm");
book.setProperty("author","George Orwell");
System.out.println("Book: " + book.getProperty("title") + " by " + book.getProperty("author"))
You've created your Book as an object.
So, treat it like an object and add getters and setters.
In this case, that would be a method, getTitle() and a separate method getAuthor().
For more information on getters and setters, see the responses to this previous StackOverflow post
You can use reflection:
Field f = bookA.getClass().getDeclaredField("title");
f.setAccessible(true);
String title = (String) f.get(bookA);
System.out.println(title);
First of all, your code won't work because title is private. Second, I have no idea why you set Book class as static. Last, this (Java) is object oriented programming, so treat it like an object.
When you create a class you also add Getters & Setters to access the information inside. The code would look like this:
Class:
public class Book {
private String author;
private String title;
public Book (String author, String title) {
this.author = author;
this.title = title;
}
}
public String getTitle(){
return this.title;
}
public String getAuthor(){
return this.author;
}
Accessing the data:
Book bookA = new Book("George Orwell","Animal Farm")
System.out.print("Book: " + bookA.getTitle() + " by " + bookA.getAuthor());
This would return :
Book: Animal Farm by George Orwell
If you see these few lines from your code:
private String author; // both are private variables
private String title;
Here author and title both are private String . So you can't access these properties outside of the class.
So, you'll need to add public getters and setters that can be used to access the properties.
you should change you Object class.. add getter and setter method..
here is example :
public class Book{
String myauthor;
String mytitle;
public Book (String author, String title){
myauthor=author;
mytitle=title;
}
public void setAuthor(String Autor){
myauthor=author;
}
public String getAuthor(){
return myauthor;
}
}
and create setter and getter for 'title' too..
if you want to get the title / author, just simply call
Book.getAuthor();
If you don't want to have getter/setter method for your class ;you can define access modifier as protected with static keyword.For example is:
under com.test package-There are two class.One is Book class and other is BookInSamePackage class.In Book class;if you define attribute title as protected static String title then in BookInSamePackage class ;You can access like that :'Book.title'.If you want to use this title attribute in class of another package;then this class need to extend Book class and can access like this way:Book.title in child class of another package.
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.
package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.
class Person {
String name = “No name";
public Person(String nm) { name = nm; }
}
class Employee extends Person {
String emplD = “0000”;
public Employee(String id) { empID = id; }
}
public class EmployeeTest {
public static void main(String[ ] args)
{
Employee e = new Employee(”4321”);
System.out.println(e.empID);
}
}
The constructor of Employee must call its super constructor, the constructor of Person.
public class Person
{
private String name;
public Person(String nm)
{
this.name = nm;
}
public String getName()
{
return this.name;
}
}
public class Employee extends Person
{
private String emplD;
public Employee(String nm, String id)
{
super(nm);
this.empID = id;
}
public String getId()
{
return this.empID;
}
}
public class EmployeeTest
{
public static void main(String[] args)
{
Employee e = new Employee("Some Name", "4321");
System.out.println(e.getID());
}
}
Change “No name’ into “No name" (closing quotes)
Maybe it's here:
String name = “No name’;
should it be:
String name = "No name";
Also, I'm not sure if this is the editor that you've pasted it in from doing this, but this is wrong too:
Employee e = new Employee(”4321”);
should be:
Employee e = new Employee("4321");
A number of things:
You're using the wrong kind of quote characters around your strings. You need to use ". Not “, ', or ”.
Your Person class has no default constructor. Because of this you must explicitly call super("some name"); as the first line of your Employee constructor (I would suggest adding a constructor that takes both name and employeeId as parameters).
You declared the property as emplD (with a lower-case L character), but you try to assign to it as empID (with an uppercase I character). You can call it whatever you want, but the name needs to match in both places.
Your object design violates the basic principles of encapsulation. The name and empID properties should be private fields, and if external classes need access to these values, then you should provide the appropriate public getter methods. In other words, instead of e.empID you should be able to say e.getEmpID().
It is generally not good coding style to define multiple classes in a single file, particularly when all of them are meant to be publicly accessible.
Change this line
String name = “No name’;
to:
String name = “No name";
check your closing qoutes.
Your empID field is not public / there is no accessor method for it / it is not defined as a property. Also don't expect people to help if you provide absolutely no information on the error other than the source code and a vague post title.
You have to call the constructor of the superclass (Person) in the constructor of the class `Employeesuper(id); Please find the correct code below.
public Employee(String id) {super(id);empID =id;
Calling a super class constructor would fix the issue !
public class Person {
String name = "No name";
public Person(String nm) { name = nm; }
}
public class Employee extends Person {
String empID = "0000";
public Employee(String id) {
super("Some Name");
empID = id; }
}
public class EmployeeTest {
public static void main(String[] args){
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}