Java Constructor instances not reading input [duplicate] - java

This question already has answers here:
Java string returns as null
(4 answers)
Closed 7 years ago.
I have just started learning java and I was given a pretty simple assignment on constructors and instances. For some reason my instances are not being set when they are created and only when I call the set methods. Can you please help me out I've been stuck for a while now with no where to go.
package hka437documents;
/**
*
* #author Henry
*/
public class Hka437Documents{
public static class Documents {
/**
* #param args the command line arguments
*/
private String title;
private String author;
private String body;
private int version;
public Documents(String title, String author){
version = 0;
}
public Documents(String title, String author, String body){
version = 1;
}
public void setTitle(String title){
this.title = title;
version++;
}
public void setAuthor(String author){
this.author = author;
}
public void setBody(String body){
this.body = body;
version++;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
public String getBody(){
return body;
}
public int getVersion(){
return version;
}
}
public static void main(String[] args) {
Documents document1 = new Documents("Another Life", "Sally Smith");
document1.setBody("The grass is always greener on the other side.");
Documents document2 = new Documents("Final Word", "Karen Jones", "We should plan for the worst and hope for the best.");
document2.setTitle("Final Words");
System.out.println("document1:");
System.out.println("Title: "+ document1.getTitle());
System.out.println("Author: "+ document1.getAuthor());
System.out.println("Body: "+ document1.getBody());
System.out.println("Version: "+ document1.getVersion());
System.out.println("\ndocument2:");
System.out.println("Title: "+ document2.getTitle());
System.out.println("Author: "+ document2.getAuthor());
System.out.println("Body: "+ document2.getBody());
System.out.println("Version: "+ document2.getVersion());
}
}
When I run the program I get null on the print statements for all of them except for the document1+2 version, document1 body and document2 title. These are the ones that had variables set with the set methods.

Look here:
public Documents(String title, String author){
version = 0;
}
public Documents(String title, String author, String body){
version = 1;
}
Your constructors only initialize version.
You have to add:
this.title = title;
this.author = author;
in the first, and:
this.title = title;
this.author = author;
this.body = body;
In the second.

you have to set atributes with params values in the constructor:
public Documents(String title, String author){
version = 0;
this.title = title;
this.author = author;
}
public Documents(String title, String author, String body){
version = 1;
this.title = title;
this.author = author;
this.body= body;
}

You actually want to set the fields in the constructor, they won't just be copied by magic. Right now they are just being ignored. You'd want a change like the following in both constructors:
this.title = title;
this.author = author;
You also want something similar to set body as well.
this.body = body;

Related

Java changing instance type to already created class type

I'm new to Java and currently I'm learning constructor. So I have a Person class
class Person {
private String name;
private double height;
Person(String name, double height) {
this.name = name;
this.height = height;
}
}
and a Book class
public class Book {
private String author;
private String title;
public Raamat(String author, String title) {
this.author = author;
this.title = title;
}
}
and a Test class
public class TestBook {
public static void main(String[] args) {
Book harryp = new Book("Rouling", "Harry Potter");
}
}
My task is to change Book class, so that author is Person-type instead of String-type like this:
private String author --> private Person author
So the Book class will look like this:
public class Book {
private Person author;
private String title;
public Book(String author, String title) {
this.author = author;
this.title = title;
}
}
So basically it should get author's name from Person's constructor? Or how does it work? And how should I modify Test class for it to work?
You'll have to initialize the Person object first.
Person author = new Person("foo", 100d);
Then you can change the Book class as follow:
public class Book {
private Person author;
private String title;
public Book(Person author, final String title) {
this.author = author;
this.title = title;
}
}
And finally initialize the Book object as follows:
Person author = new Person("foo", 100d);
Book b = new Book(author, "My Title");
Solution 1:
public class Book {
private Person author;
private String title;
public Book(String author, String title) {
this.author = new Person(author);
this.title = title;
}
}
class Person {
private String name;
private double height;
public static final double DEFAULT_HEIGHT = 0.0;
Person(String name, double height) {
this.name = name;
this.height = height;
}
Person(String name) {
this(name, DEFAULT_HEIGHT);
}
}
You have to add one more constructor into your Person class, and instantate a new Person when you pass String author into Book
Book b = new Book("Mike", "Book Title");
Alternatively, pass person instance into Book and access name by getName():
public class Book {
private Person author;
private String title;
public Book(Person author, String title) {
this.author = author.getName();
this.title = title;
}
}
So basically it should get author's name from Person's constructor?
Not necessarily. You can keep the client code simple by creating the Person directly in the Book constructor.
public class Book {
private Person author;
private String title;
public Book(String authorName, double height, String title) {
this.author = new Person(authorName, height);
this.title = title;
}
}
You would call it :
Book book = new Book("author", 170, "book title");
Yon can also accept a Person as parameter in the constructor :
public Book(Person author, String title) {
this.author = author;
this.title = title;
}
And in this case, the client code should pass a Person and not a String and a double.
Person author = new Person("author", 170)
Book book = new Book(author, "book title");
You can even propose both by overloading the constructor.
In fact, the way that you should use is the way that is the most practical for the class clients.
author should be a new Person, whose name is drawn from the name field of Book's constructor.
There are two ways you can solve this:
By changing the parameter type on your constructor to Person:
public class Book {
private Person author;
private String title;
public Raamat(Person author, String title) {
this.author = author;
this.title = title;
}
}
By initializing the author on the constructor:
public class Book {
private Person author;
private String title;
public Raamat(String author, String title) {
this.author = new Person(author);
this.title = title;
}
}

Constructor is Underfined

I am getting an error saying my constructor Book(String, int) is undefined in my Dictionary class. I check everything else and try to redo my programs still has an error. Any solutions of fixing this issue?
Book Class:
public class Book{
private String author;
private int numPages;
public Book(int code, String title, double price, int quantity, String author, int numPages){
this.author = author;
this.numPages = numPages;
}
//Getters
public String getAuthor(){
return this.author;
}
public int getNumPages(){
return this.numPages;
}
//Setters
public void setAuthor(String author){
this.author = author;
}
public void setNumPages(int numPages){
this.numPages = numPages;
}
//toString
#Override
public String toString(){
String outputBookDes = "";
outputBookDes += "Author: "+ this.author;
outputBookDes += "Number Pages: "+ this.numPages;
return outputBookDes;
}
}
Dictionary Class:
public class Dictionary extends Book{
private String language;
private int numDefinitions;
public Dictionary(String author, int numPages, String language, int numDefinitions){
super(author,numPages);
this.language = language;
this.numDefinitions = numDefinitions;
}
// Getters
public String getLanguage(){
return this.language;
}
public int getNumDefinitions(){
return this.numDefinitions;
}
//Setters
public void setLanguage(String language){
this.language = language;
}
public void setNumDefinitions(int numDefinitons){
this.numDefinitions = numDefinitions;
}
//Ratio method
public double getRatio(){
double ratioTotal = this.numDefinitions / getNumPages();
return ratioTotal;
}
}
As you are calling
super(author,numPages);
in child class Dictionary,
you need to define another constructor in Book class like,
public Book(String author,int numPages) {
this.author = author;
this.numPages = numPages;
}
to get this error solved.
according to your only constructor:
public Book(int code, String title, double price, int quantity, String author, int numPages)
In your main method try:
Book book = new Book(12, "title", 34d, 56, "author", 78);
instead of:
Book book = new Book("34", 56);

Putting several textfields into one arraylist

I´m quite the noob when it comes to coding. I am about to create a programme where you can add the title (String), author (String), release year (int) and genre (String) of a book from writing it in textfields. These things are supposed to be saved in an arraylist. I can not figure out how to add all of these items to the same slot in the arraylist. Please help as fast as possible.
So you need to create a book class with getters/setters.
public class Book {
public String title;
public String author;
public int year;
public String genre;
}
Then you create a Book
Book book = new Book();
use the setters to set the instance variables (or you can do this when creating book object if you have a constructor with appropriate parameters)
book.setAuthor("R.L.Stein");
once all the fields are set you add the book to an array list.
ArrayList<Book> books = new ArrayList<Book>();
books.add(book);
To print, you should have a toString() method in you book class
public String toString(){
return "Title: "+title+"\nAuthor: "+author+"\nYear: "+year+"\nGenre: "+
genre;
}
Now when you print a book object it will show all its information. It's best to then use a loop to iterate through the list and print each book in books
for(int i=0; i<books.size(); i++){
System.println(books.get(i));
}
Building off of my comment in the original post, here's what your book class should look like:
public class Book {
private String title;
private String author;
private String genre;
private int releaseYear;
public Book(String title, String author, String genre, int releaseYear) {
this.title = title;
this.author = author;
this.genre = genre;
this.releaseYear = releaseYear;
}
public String getTitle() { return this.title; }
public String getAuthor() { return this.author; }
public String getGenre() { return this.genre; }
public int getReleaseYear() { return this.releaseYear; }
}
Now all you need to do is create multiple instances of these classes, and add them into your ArrayList.
Here's a link with some examples of how to use ArrayLists: http://beginnersbook.com/2013/12/how-to-initialize-an-arraylist/
You can do this in two ways.
Create a class containing the title (String), author (String), release year (int) and genre (String) and create a new instance of that class and add it to the array. Here is a javadoc on classes.
(Not recommended, but still works) You can create an array list with a size of 4. The array will be an Object to support the integer. Example: Object[] obj = new Object[]{"title", "author", 2015, "genre"}; You can then take the array and add it to the other array you wanted to add this information to.
If you want to go with choice two and create a class here is an example:
public class Book {
private String title, author, genre;
private int releaseYear;
public Book(String title, String author, int releaseYear, String genre){
this.title = title;
this.author = author;
this.releaseYear = releaseYear;
this.genre = genre;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getGenre() {
return genre;
}
public int getReleaseYear() {
return releaseYear;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}
}
If you wanted to create a new instance of the Book class you would do:
Book book = new Book("title", "author", 2015, "genre");

using method to add book to a library array

in this program i need to add 4 books to a library.The code is for my book class but i need to make a method with 4 arguments in another file in my library class that will add the books into a library array.There is a third file for the main where i will print this all out but i just cant figure this out.
Example of book: author-clowney, title-individualism,price-5.50,isbn-978-52-234-43-012
private String author;
private String title;
private double price;
private int isbn;
public book(String a, String t, double p, int i){
author=a;
title=t;
price=checkPrice(p);
isbn=checkIsbn(i);
}
//First and foremost you need to create the book object
public class Book extends Library{
private String author;
private String title;
private double price;
private int isbn;
//Null Constructor-this creates
public book() {
this.author = abcd;
this.title = abcd;
this.price = 0.0;
this.isbn = 0000000;
}
//Now its time for the book with parameters
public book(String a, String t, double p, int i){
author = a;
title = t;
price = p;
isbn = i;
}
//Now it's time to set and get the above values you want
public void setAuthor(String author){
this.author = author;
}
public String getAuthor(){
return this.author;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setPrice(double price){
this.price = price;
}
public double getPrice(){
return this.price;
}
public void setIsbn(int isbn){
this.isbn = isbn;
}
public double getIsbn(){
return this.isbn;
}
//Now you are going to want to toString(), that way you can display the books in the library
public String toString() {
//Im assuming you have learned that Library is your super class and has a toString() as well
return(super.toString()+ "Book Author: " + this.author + "Book Title: " + this.title + "Book Price: " + this.price + "Book ISBN: " + this.isbn);
}
}
//Now simply call this method within your main method to display books in Output!!
//Hope this helps, if you have further questions please leave below!!

ArrayList lists null instead of instances of the object [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public class Library{
private ArrayList<Book> books = new ArrayList<Book>();
public void addBook()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter title of the book: ");
String title = sc.nextLine();
System.out.println("Enter the author: ");
String author = sc.nextLine();
String bookID = bookID();
Book b = new Book(author,title,bookID,true);
books.add(b);
System.out.println( title + " by "+ author +" added to library.");
System.out.println("Book ID: " + bookID);
}
public void listBooks()
{
for (Book temp : books)
{
if (temp.loanStatus() == true) System.out.print("*");
System.out.println(temp.getTitle() + " by " + temp.getAuthor()+
"ID: " + temp.getID());
}
}
}
Here's my Book class:
public class Book {
private String author;
private String title;
private String ID;
private boolean loanRecord = true;
public Book(String au, String titl, String id, boolean loan)
{
au = author;
titl = title;
loan = loanRecord;
id = ID;
}
public String getTitle()
{
return title;
}
public String getAuthor()
{
return author;
}
public String getID()
{
return ID;
}
public boolean loanStatus()
{
return loanRecord;
}
public void checkoutBook()
{
loanRecord = false;
}
public void returnBook()
{
loanRecord = true;
}
}
For some reason, when I call my listBooks() method to list all of the books added to the books ArrayList, every Book object that I have added comes out as null instead of the desired string instances that I expect.
You swapped your assignments in your constructor.
It should be:
public Book(String au, String titl, String id, boolean loan){
author = au;
title = titl;
loanRecord = loan;
ID = id;
}
As a quick note, you could override the toString method in your Book class and simply do:
for (Book temp : books){
if (temp.loanStatus())
System.out.print("*");
System.out.println(temp);
}
The constructor is wrong:
public Book(String au, String titl, String id, boolean loan)
{ au = author; titl = title; loan = loanRecord; id = ID; }
should be:
public Book(String au, String titl, String id, boolean loan)
{ author = au; title = titl; loanRecord = loan; ID = id; }
Another thing to consider would be to override the default toString() method in the Book class. Then you could print the objects using just:
for(Book b : books)
System.out.println(b);
I would suggest you to refactor your Book class ,
public class Book {
private String author;
private String title;
private String ID; // the name can be changed to id , if you are fine with it
private boolean loanRecord = true;
public Book(String author, String title, String id, boolean loan) {
this.author = author;
this.title = title;
this.ID = id;
this.loanRecord = loan;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getID() {
return ID;
}
public boolean loanStatus() {
return loanRecord;
}
public void checkoutBook() {
loanRecord = false;
}
public void returnBook() {
loanRecord = true;
}
}

Categories