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")
Related
Is it possible to construct an object given a string, toString() method, and the Class itself.
For example we have class Book.
class Book
{
// ...
String getTitle()
{
return title;
}
String getPubYear()
{
return pubYear;
}
void setTitle(String _title)
{
title = _title;
}
void setPubYear(String _pubYear)
{
pubYear = _pubYear;
}
public String toString(){
return title+" "+pubYear;
}
}
If we have the String:
"ExampleTitle 2017"
How can we create an instance of the class Book, with which has attribute:
title=ExampleTitle
pubyear=2017
We can do the following:
Book book = new Book();
String exampleString = "ExampleTitle 2017";
String[] parts = exampleString.split();
book.setTitle(parts[0]);
book.setPubYear(parts[1]);
But this is long winded. Is there a more automatic way to do this?
You can add a new constructor:
public Book(String s) {
String[] parts = s.split(" ");
if (parts.length() == 1) {
this.title = s;
} else {
this.title=parts[0];
this.pubYear(Integer.parseInt(parts[1]));
}
}
You should add NumberFormatException handling on your own but I recommend my post about it.
The above constructor will take a String, split it by a space and perform what you have done. You can use it like:
Book book = new Book("Example_title 2001");
but it's not the best approach. You should rather use standard patterns and first extract the values you want to set to your Book and then pass them to the constructor.
The good way of doing what you want will be to make another constructor:
public class Book {
public Book(String s, int y) {
this.title = s;
this.year = y;
}
}
Please change year field to int or long. Year shouldn't be a String as long as you're not using Roman numbers.
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.
What im trying to do is have the user input an index of "record" they want to append. The index will be used to look at a specific object in the array list. Everything stored in that object will be written to the input from. The user will then be able to append their input and write it back to the same object. What I'm stuck on is the taking data from the object and adding it to the form controls. I was am using
Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1);
but that gave me object instance which is not a string that I wanted.
I was told to use
#Override
public String toString() {
return genreOfMovie;
}
It worked but only for that veritable, is there a way to make it work for all the variables in the selected object?
If you have a text field (for instance for the title of the movie) I suggest you add setTitle(String newTitle) and getTitle() to your Movie class.
With this in place, you can do
textField.setText(selectedMovie.getTitle());
and, when the user clicks save,
selectedMovie.setTitle(textField.getText());
If you have more properties (genre, director, ...) I suggest you add more get-/set-methods.
Unless the class has an very obvious String-representation, the toString should only be used in debugging purposes.
If you want to get all variables data from Movie object,
either
include a method inside Movie object which appends the variables data in required format and gives as String output.
or
Write your own method which will take Movie object as an input, and calls required fields getter methods like getTitle()+getGenreOfMovie+getLength() like that and return a String object.
And important thing is to check for Null or Empty data inside those variables.
import java.util.ArrayList;
import java.util.List;
public class MovieTest {
public static void main(String[] args) {
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie("A"));
movies.add(new Movie("B"));
movies.add(new Movie("C"));
Movie movie = movies.get(1);
System.out.println(movie);
movie.setDirector("Director for B");
movie = movies.get(1);
System.out.println(movie);
}
}
class Movie {
String title;
String director;
int length;
Movie(String title) {
this.title = title;
}
public String getTitle() { return title; }
public String getDirector() { return director; }
public int getLength() { return length; }
public void setTitle(String title) { this.title=title; }
public void setDirector(String director) { this.director = director; }
public void setLength(int length) { this.length = length; }
public String toString() {
return "[" + title + "]["+ director +"][" + length + "]";
}
}
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.
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.