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 + "]";
}
}
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")
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.
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.
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.
Im learning Java and having a problem with ArrayList.
Firstly I have a class called Item, with which I create various item objects.
Then I have a class Catalogue which is an array list and should hold a list of the item objects I create.
At the moment I can manually add the items to the catalogue by invoking an addItem method on the Catalogue object and manually entering the name of the item object I want to add (item1 item2 item3 etc)
But I wanted to know if there is a way to add the items to the ArrayList automatically each time I create an item object?
I should mention, my list needs to hold an infinite amount of items, so I have not specified a size in my code.
Any help would be greatly appreciated :)
Thanks
import java.util.ArrayList;
public class Catalogue
{
private ArrayList<Item> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Item>();
}
public void addAnItem(Item item)
{
catalogue.add(item);
}
}
Use the Catalogue as an Item factory:
public class Catalogue
{
...
public Item createItem()
{
Item item = new Item();
catalogue.add(item);
return item;
}
...
}
Another approach: Make Catalogue singleton and let the items add themselves.
One way you could do this, is if you passed the Catalogue into the constructor of the Item class, and once the item is set up, add the item to the catalogue at that point.
It may look something like this
public Item(Catalogue catalogue) {
// set up item here
// finally add item to the catalogue
catalogue.addAnItem(this);
}
I have put some comments at Matten and Codemwnci's answers, and here is an explanation of them.
Codemwnci suggests that you should not be able to construct an Item without setting its catalogue.
public class Item {
public Item(Catalog catalog) {
// set up item here
// finally add item to the catalog
catalog.addAnItem(this);
}
}
This explicit constructor removes the implicit default (no-arg) constructor, and you cannot construct an Item without it having a valid, non-null catalog.
If you have various types of items, with (slightly) different behaviour, you might be better served with Matten's answer (although slightly changed here).
As an example I'm using a Book (which is your Item). My Book has a title, author, textAtTheBack, and weight.
interface Book {
String getTitle();
String getAuthor();
String getTextAtTheBack();
Long getWeight(); // in grams, can be very heavy!
}
public class Catalog {
private ArrayList<Book> catalogue;
public Book createPaperback(final String title, final String author,
final String tatb, final Long weight) {
Book b = new Book() {
String getTitle() { return title; }
String getAuthor() {return author; }
String getTextAtTheBack() {return tatb;}
Long getWeight() {return weight;}
}
catalogue.add(b);
return b;
}
public Book createEBook(final String title, final String author,
final String tatb) {
Book b = new Book() {
String getTitle() { return title; }
String getAuthor() {return author; }
String getTextAtTheBack() {return tatb;}
Long getWeight() {return 0;} // Yep - no weight!
}
catalogue.add(b);
return b;
}
}
Alternatively, you could have different catalogues:
public abstract class Catalogue {
private final List<Book> books = new ArrayList<Book>;
public abstract Book (final String title, final String author,
final String tatb, final Long weight);
/** Find the book with the given title (not null) in the current catalogue.
* #return the book, or null if not found.
*/
public void findBook(String title) {
for (Book b : books) {
if (b.getTitle().equalsIgnoreCase(title)) {
return b;
}
}
return null;
}
protected void addBookToCatalogue(Book b) {
books.add(b);
}
}
public class EbookCatalogue extends Catalogue {
public Book (final String title, final String author,
final String tatb, final Long weight) {
Book b = new Book() {
String getTitle() { return title; }
String getAuthor() {return author; }
String getTextAtTheBack() {return tatb;}
Long getWeight() {return 0;} // ignore weight
}
addBookToCatalogue(b);
return b;
}
}
In the rest of the program you can have multiple catalogues, each with a slightly different type of Book, but the program need not know that.
I think in this case the simple Constructor of codemwnci is best, but there alternative solutions if your situation warrants a more flexible solution.