trying to print a method from arraylist - java

I am trying to print title from my member class using array in my library class
public class Book gives me this error :
http://screencast.com/t/tqpJp2BF8sH
{
// instance variables - replace the example below with your own
private int x;
private Integer bookid;
private String author;
private String title;
private String ficornonfic;
/**
* Constructor for objects of class Book
*/
public Book(Integer bookID, String Author, String Title, String FictionORnonfiction )
{
bookid = bookID;
author = Author;
title = Title ;
ficornonfic = FictionORnonfiction;
x = 0;
}
public String PrintListOfBooks()
{
return title;
}
public String toString() {
return "Title:" + title + " BookId: " + bookid + " Author: " + author + ".";
}
public int getTitle() {
return this.title;
}
}
---------------------------------------------------------
this is my library class
import java.util.ArrayList;
public class Library
{
private ArrayList<Member>listOfMembers;
public Library()
{
listOfMembers = new ArrayList<Member>();
listOfBooks = new ArrayList<Book>();
}
public void storeMember(Member Member)
{
listOfMembers.add(Member);
}
public int numberOfMembers()
{
return listOfMembers.size();
}
public void listMembers()
{
for (int item=0; item<listOfMembers.size(); item++ ) {
Member m = listOfMembers.get (item);
System.out.println(m.GetWholeName());
}
}
public Member findMember(int id) {
for(Member member : listOfMembers) {
if (member.getId() == id) {
return member;
}
}
return null;
}
private ArrayList<Book>listOfBooks;
public void storeBook(Book Book)
{
listOfBooks.add(Book);
}
public int numberOfBooks()
{
return listOfBooks.size();
}
public void listBooks()
{
for (int item=0; item<listOfBooks.size(); item++ ) {
Book b = listOfBooks.get (item);
System.out.println(b.PrintListOfBooks());
}
}
public Book findBook(string title) {
for(Book book : listOfBooks) {
if (book.getId() == id) {
return book;
}
}
return null;
}
}
I am trying to print title from my member class using array in my library class
public class Book gives me this error :
http://screencast.com/t/tqpJp2BF8sH

The title is a String, not an int. You can change the method signature to match the field type:
public String getTitle() {
return this.title;
}

First, as others have noted your title is a String not an int. So change the return type of getTitle() (or remove it altogether). Because it appears like you've correctly overridden toString() in Book to get all the information, and you could iterate the contents of your List with a for-each loop. Something like,
for (Book b : listOfBooks) {
System.out.println(b);
}
which is equivalent to
for (int i = 0; i < listOfBooks.size(); i++) {
Book b = listOfBooks.get(i);
System.out.println(b.toString());
}
Finally in Java, by convention, method names start with a lower case letter.

You are essentially telling the program to return an Integer when the value you wish to return is a String.
If you change int to String, the error will go away.
public String getTitle() {
return this.title;
}

Related

Method to count the number of books of an author

So I need to create 3 classes "Book"(with fields author, title and body, as string), "Shelf"(with fields id (string) and books (array) and "Library". Then I shall create a method "countAuthor".which counts (and returns as an int) the number of books in the library written by an author whose name (String) is passed as an argument to the method:
class Book {
private String author;
public String getAuthor() {return author;}
private String title;
public String getTitle() {return title;}
private String body;
public String getBody() {return body;}
}
class Shelf {
private String id;
public String getId() {return id;}
private int[] books;
public int[] getBooks() {return books;}
}
class Library {
private int[] shelves;
public int[] getShelves() {return shelves;}
public int countAuthor(String authorName) { // returns the number of books in the library written by author whose name (String)
//is passed as an argument to the method.
int a = ;
return a; // a is the number of books of the author
}
}
After all, in the class (where the main method is stated), I need to add the necessary code and the program overall shall print the number of books an author has written. This is the class of the main method:
public class Exercise {
public static void main(String[] args) {
Shelf shelf1 = new Shelf("Shelf1",
new Book[] {
new Book("Babel", "Odessa Tales", "babelode"),
new Book("Joyce", "Ulisses", "joyceuli")
});
Shelf shelf2 = new Shelf("Shelf2",
new Book[] {
new Book("Mann", "Dr Faustus", "mannfau"),
new Book("Babel", "Red Cavalry", "babelred")
});
Library lib = new Library(
new Shelf[] { shelf1, shelf2 });
System.out.println("# of books by this author: " + lib.countAuthor("Babel"));
}
}
Which should print # of book by this author: 2
Where I am confused with is what to add to the countAuthor() method. And if I need anything in addition to the method. I am pretty new to Java so I still get confused with some structures, especially with the loops.
Here it is. In your code you are missing constructors that you are trying to use so I added them. The logic of counting the books is just go through all the shelves in the lib and count all the books on these shelves with the author name.
public class Exercise {
public static void main(String[] args) {
Shelf shelf1 = new Shelf("Shelf1", new Book[]{
new Book("Babel", "Odessa Tales", "babelode"),
new Book("Joyce", "Ulisses", "joyceuli")});
Shelf shelf2 = new Shelf("Shelf2",
new Book[]{
new Book("Mann", "Dr Faustus", "mannfau"),
new Book("Babel", "Red Cavalry", "babelred")
});
Library lib = new Library(new Shelf[]{shelf1, shelf2});
System.out.println("# of books by this author: " + lib.countAuthor("Babel"));
}
}
class Book {
public Book(String author, String title, String body) {
this.author = author;
this.title = title;
this.body = body;
}
private String author;
public String getAuthor() {
return author;
}
private String title;
public String getTitle() {
return title;
}
private String body;
public String getBody() {
return body;
}
}
class Shelf {
public Shelf(String id, Book[] books) {
this.id = id;
this.books = books;
}
private String id;
public String getId() {
return id;
}
private Book[] books;
public Book[] getBooks() {
return books;
}
}
class Library {
public Library(Shelf[] shelves) {
this.shelves = shelves;
}
private Shelf[] shelves;
public Shelf[] getShelves() {
return shelves;
}
public int countAuthor(
String authorName) { // returns the number of books in the library written by author whose name (String)
//is passed as an argument to the method.
int count = 0;
for (Shelf shelf : shelves) {
for (Book book : shelf.getBooks()) {
if (book.getAuthor().equals(authorName)) {
count++;
}
}
}
return count; // a is the number of books of the author
}
}
Output:
# of books by this author: 2
As I can see from your question, the structure will be like this.
Library can have many Shelf and in every Shelf there are many books.
So to count the no of books for a particular author, first you need all the books.
It will be something like this.
public int countAuthor(String author) {
int result = 0;
for(Shelf shelf : shelves) {
for(Book book : shelf.getBooks()) {
if(author.equals(book.getAuthor()) {
result++;
}
}
}
return result;
}

Superclass overriding Subclass with default values from constructor in Java

I have an assignment and my superclass default values always override the values I pass in the Test main method. In the debugger, i see the passing of the productNumber(1234) and productTitle("Daughter"), but then it's overridden with the default values. Any thoughts, i keep making minor changes, checking for changes, still the same results.
Product Superclass
public abstract class Product {
private int productNumber;
private String productTitle;
//Two constructors required
public Product(){
productNumber = 0;
productTitle = "";
}
public Product(int productNumber, String productTitle) {
this.productNumber = productNumber;
this.productTitle = productTitle;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public int getProductNumber() {
return productNumber;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
public String getProductTitle() {
return productTitle;
}
//Override toString() required
#Override
public String toString() {
return productNumber + " " + productTitle;
}
// Required Product class declares abstract method with this signature: public String getDisplayText()
public abstract String getDisplayText();
//Override equals() required
#Override
public boolean equals(Object object) {
if (object instanceof Product) {
Product product2 = (Product) object;
if (productNumber == (product2.getProductNumber()) &&
productTitle.equals(product2.getProductTitle())){
return true;
}
}
return false;
}
}
Music Subclass extends Product Superclass
public class Music extends Product {
private String artist;
private String style;
private String medium;
public Music() {
super();
artist = "";
style = "";
medium = "";
}
public Music(int productNumber, String productTitle, String artist, String style, String medium) {
super();
this.artist = artist;
this.style = style;
this.medium = medium;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
#Override
public String getDisplayText() {
return super.toString() + " by " + artist + " " + style + " " + medium;
}
#Override
public boolean equals(Object object){
if (object instanceof Music){
Music m = (Music) object;
if (artist.equals(m.getArtist()) &&
style.equals(m.getStyle()) &&
medium.equals(m.getMedium())){
return true;
}
}
return false;
}
}
Print String
public class Test {
public static void main(String[] args) {
// Expected result: 1234 Daughter by Pearljam Alternative online
Music music1 = new Music(1234,"Daughter", "Pearljam","Alternative","online");
System.out.println(music1.getDisplayText());
}
}
you are not passing values from subclass to your parentclass
instead of super() you need to do below -
super(productNumber,productTitle);
update needed in your code :-
public Music(int productNumber, String productTitle, String artist, String style, String medium) {
super(productNumber,productTitle);
this.artist = artist;
this.style = style;
this.medium = medium;
}
You need to pass productNumber and productTitle in the super(..., ...) call inside the Music constructor up to the parent class.
You need to invoke
super(productNumber, productTitle)
inside the Music constructor to pass the parameters to its parent.

Returning an object corresponding to a class

So i have 2 classes, and in the class race i have a method ( public Athlete getAthlete(int codAthlete) ) that
should return the object corresponding to the Athlete with the code passed by parameter, but i am not sure how to
implement it. Can someone give me a hand?
public class Athlete {
private int codAthlete;
private String name;
public Athlete(int codAthlete){
this.codAthlete = codAthlete;
}
public int getCodAthlete() {
return this.codAthlete;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getInformation() {
return "Code: " + this.codAthlete +
" Name " + this.name;
}
}
.
public class Race {
private String idRace;
private Set<Athlete> athletes;
public Race(String idRace) {
athletes = new HashSet<>();
this.idRace = idRace;
}
public String getIdRace () {
return this.idRace;
}
public Athlete getAthlete(int codAthlete){
for(Athlete a: Athlete){
if(a.getCodAthlete() == codAthlete)
a.getInformation();
}
return (????);
// Returns the object corresponding to the Athlete with the code passed by parameter.
}
}

Trying to delete an object from Arraylist - still possible to access object

i'm trying to add function to delete objects from my array list (first i want to generate unique random ids for these objects:
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class Medium {
public Medium(){
this.id = generateID();
System.out.println("ID: " + id);
mlist.add(this);
}
protected int generateID() {
Random random = new Random();
int id;
do {
id = 100 + (random.nextInt(999-100));
} while(idlist.contains(id));
idlist.add(id);
return id;
}
protected boolean delete(Medium delElem) {
boolean isDeleted = false;
ListIterator<Medium> it = mlist.listIterator();
while(it.hasNext()) {
it = mlist.listIterator();
Medium next = it.next();
if(delElem.getID() == next.getID()) {
delElem = next;
mlist.remove(delElem);
delElem = null;
if(delElem == null) {
System.out.println("Succesfull deleted");
}
isDeleted = true;
break;
}
}
return isDeleted;
}
protected int getID() {
return id;
}
public String getTitle() {
return title;
}
protected ArrayList<Medium> mlist = new ArrayList<Medium>();
private ArrayList<Integer> idlist = new ArrayList<Integer>();
protected String title;
protected final int id;
}
I'm not sure if i understand this properly, but if i set the delElem = the object that meets the equal id, delete my object and set it = null, the object should not reference anymore. But if I test it in my main function, for example book.getTitle(), the title will be printed. I think it's because it's just a local object in my function. How can I globally delete my object in a function and return a boolean value if the object was removed succesfully?
Thanks!
It has already been stated in the comments that you usually don't delete objects manually (by setting them to null). The garbage collection will do it's job when they are not needed anymore.
The weird thing in your code is that the medium adds itself to the list. Why don't you create another class that represents a book shelf. This way you can implement methods on the bookshelf to add or remove books:
package com.example;
import java.util.ArrayList;
import java.util.Random;
public class BookShelf {
protected ArrayList<Medium> mlist = new ArrayList<Medium>();
private ArrayList<Integer> idlist = new ArrayList<Integer>();
private class Medium {
protected int id;
protected String title;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public Medium addMedium(String title) {
Medium medium = new Medium();
medium.setId(this.generateID());
medium.setTitle(title);
this.mlist.add(medium);
return medium;
}
protected int generateID() {
Random random = new Random();
int id;
do {
id = 100 + (random.nextInt(999 - 100));
} while (idlist.contains(id));
idlist.add(id);
return id;
}
protected boolean delete(Medium delElem) {
boolean isDeleted = false;
for (Medium medium : mlist) {
if (medium.getId() == delElem.getId()) {
mlist.remove(medium);
isDeleted = true;
break;
}
}
return isDeleted;
}
public ArrayList<Medium> getAllBooks() {
return this.mlist;
}
#Override
public String toString() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("Books in the shelf: " + this.getAllBooks().size() + "\n");
for(Medium medium : this.getAllBooks()) {
strBuilder.append("Title: " + medium.getTitle() + "\n");
}
return strBuilder.toString();
}
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf();
//Add two books to the shelf
Medium medium1 = bookShelf.addMedium("Book 1");
Medium medium2 = bookShelf.addMedium("Book 2");
System.out.println(bookShelf.toString());
//Delete one
bookShelf.delete(medium1);
System.out.println(bookShelf.toString());
}
}

Calling method from an instance of a class

I'm new at java so sorry for the inconsistencies.
I'm creating a library program and I'm having trouble calling a method from the Book class in the Patron class.
In the Patron class I have a method checkOutBook() which a user can input a book to check out. However I'm having trouble accessing the setStatus() method in Book. I know I have to call it against an instance of the Book class but I'm unsure how to do so with a user inputed string.
import java.util.ArrayList;
import java.util.Collections;
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 > ();
public String title;
public String author;
public Book book;
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(Book bookCheckOut) {
this.book = bookCheckOut;
}
}
public void CheckOutBook() {
Scanner inputread = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter full patron name: ");
String borrower = inputread.nextLine();
System.out.println("Enter book title to check out: ");
String bookCheckOut = inputread.nextLine();
if (Book.BookList.contains(bookCheckOut)) {
Book.BookList.remove(bookCheckOut);
Book.setStatus("OUT"); //error message
Book.setBorrower(borrower); //error message
System.out.println("----------" + bookCheckOut + " has been checked out!----------");
System.out.println("-------------------BOOK STATUS:---------------------");
System.out.println("Book Title: " + bookCheckOut);
System.out.println("Book Status: Checked out");
System.out.println("Borrower: " + borrower);
System.out.println("Due Date: " + dueDate);
System.out.println("----------------------------------------------------");
I attempted to do this but it didn't work either :(
Thank you for your help!
Book bookCheckOut = new Book(bookCheckOut); //error: constructor Book(book) undefined
bookCheckOut.setStatus("OUT");
bookCheckOut.setBorrower(borrower);
bookCheckOut.setBook(bookCheckOut);
Book bookCheckOut = new Book(bookCheckOut); <~ I think you are getting confused because you already defined bookCheckOut as a String from the scanner and in this line you are setting it to a book object. Try changing the first bookCheckOut in this line to something else. Syntax: Book bookObjectName = new Book("String");
For the setStatus and setBorrower error you are trying to use those methods as if they were static. To fix this don't call Book.setStatus but replace Book with your instantiated book object name. Example: Book b = new Book ("Asd","abc"); b.setStatus("xyz");
Also, why do have two scanners?
Change Book.BookList from ArrayList<String> to Map<String, Book> as shown below:
public class Book {
static Map<String, Book> BookList = new HashMap<>();
...
Then in CheckOutBook() change:
if (Book.BookList.contains(bookCheckOut)) {
Book.BookList.remove(bookCheckOut);
Book.setStatus("OUT"); //error message
Book.setBorrower(borrower); //error message
...
To:
Book book = Book.BookList.get(bookCheckOut);
if (book != null) {
Book.BookList.remove(bookCheckOut);
book.setStatus("OUT");
book.setBorrower(borrower);
...

Categories

Resources