I'm trying to make a copy of a BookOrder that I've already created, however, it isn't creating properly. So far, I have this.
public class BookOrder
{
private String author;
private String title;
private int quantity;
private double costPerBook;
private String orderDate;
private double weight;
private char type; //R,O,F,U,N
public BookOrder (String author, String title)
{
}
public BookOrder(String author, String title, int quantity, double costPerBook, String orderDate, double weight, char type)
{
this.author= author;
this.title= title;
this.quantity= quantity;
this.costPerBook= costPerBook;
this.orderDate= orderDate;
this.weight= weight;
this.type=type;
}
public BookOrder(BookOrder bookOrder)
{
}
However, when I try to copy this here:
public class TestBookOrder
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Utility.myInfo("11/5,2013", "Project4");
Utility.pressEnterToContinue();
Utility.clearScreen();
BookOrder BookOrder1 = new BookOrder("Jonathan", "Book1", 12, 6.75, "11/5/2013", 8.75, 'r');
System.out.print(""+ BookOrder1.invoice());
BookOrder copyA = new BookOrder(BookOrder1);
BookOrder copyB= new BookOrder(BookOrder1);
copyB.adjustQuantity(-5);
System.out.print("\n"+ copyB.invoice());
System.out.print("\n"+ copyA.invoice());
}
}
it just returns the invoice for copyA and copyB as null and 0. Anyone know what code needs to be within the copy method?
To make this work, you need to change following code. This will create a new Object and will populate same with BookOrder value passed as input. Hope this answers your doubt.
public BookOrder(BookOrder bookOrder)
{
this.author= bookOrder.getAuthor();
this.title= bookOrder.getTitle();
this.quantity= bookOrder.getQuantity();
this.costPerBook= bookOrder.getCostPerBook();
this.orderDate= bookOrder.getOrderDate();
this.weight= bookOrder.getWeight();
this.type=bookOrder.getType();
}
You need to copy the values of the parameter BookOrder into your current parameters.
e.g.,
class Foo {
private int bar;
public Foo(Foo foo) {
this.bar = foo.bar;
// same for other fields if they exist.
}
}
Incidentally, you will want to fix this:
public BookOrder (String author, String title)
{
}
You're throwing out the parameters passed into this constructor, completely ignoring them.
Edit: this was already explained to you in a previous answer to a previous question on the same assignment!
That's because you need to assign all the fields from the passed object to the current object, in the copy constructor.
public BookOrder(BookOrder bookOrder) {
this.author = bookOrder.getAuthor(); // since they are private and thus you need getter to get the values
this.title = bookOrder.getTitle();
this.quantity = bookOrder.getQuantity();
this.costPerBook = bookOrder.getCostPerBook();
this.orderDate = bookOrder.getOrderDate();
this.weight = bookOrder.getWeight();
this.type =bookOrder.getType();
}
Related
I'm trying to print an arraylist that is in one class, based on one of the parameters from another class. Is this possible?
import java.util.ArrayList;
public class TVShow {
private String title;
private String summary;
private String releaseDate;
private ArrayList<Episode> episodeList;
public TVShow(String title, String summary, String releaseDate) {
this.title = title;
this.summary = summary;
this.releaseDate = releaseDate;
this.episodeList = new ArrayList<>();
}
public void addEpisode(Episode episode) {
episodeList.add(episode);
}
public printEpisodesInSeason(int seasonNr) {
// How can I make this method access the other class and
// print the episodeList by season number?
for (Episode episode : episodeList) {
return System.out.println(episode.);
}
}
}
public class Episode {
private int episodeNr;
private int seasonNr;
private String eTitle;
private int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
}
EDIT: I think I misinterpreted the question. You want to only print the episodes from a specific season. This can be done by applying the filter function on the episodeList as follows:
for (Episode episode : episodeList.stream().filter(episode -> episode.getSeasonNr() == seasonNr).collect(Collectors.toList()))
{ ... }
This is ofcourse assuming you apply the getter setter pattern as described below before I edited the answer.
The filter function takes an anonymous function and applies it to all members of a collection. This way, only the episodes which have a season number that is supplied by the user are returned. Then, the foreach loop iterates over the resulting collection.
You could either make the members of Episode public by defining:
public class Episode {
public int episodeNr;
public int seasonNr;
public String eTitle;
public int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
}
But this is seen as bad practice. The better way to do it is by defining methods in your Episode class to return the value of the class' fields like for example:
public class Episode {
public int episodeNr;
public int seasonNr;
public String eTitle;
public int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
public String getTitle() {
return this.eTitle;
}
}
This practice is called getters and setters and it positively impacts the encapsulation of the code. You could then obtain the value of the Episode's members by calling, for example episode.getTitle().
I have two classes ("Startup.java" and "Book.java").
My goal is to print all object(s) from "Book.java".
To call the view() method, I initialized a new 'book-object'. The problem is:
if I call "book.view", it print's '0nullnull0' (I know, it's because of the constructor), I have no idea how to fix it. Here you can see the code:
package array;
import java.util.*;
public class Startup{
public static void main(String[] args) {
Book book = new Book(0, null, null, 0);
book.view();
}
package array;
public class Book {
private int number;
private String title;
private String language;
private int price;
public Book(int number, String title, String language, int price) {
this.number = number;
this.title = title;
this.language = language;
this.price = price;
}
public void add() {
Book b1 = new Book(1, "title", "de", 2);
}
public void view() {
System.out.println(number + title + language + price);
}
}
You have initialized your object using
Book book = new Book(0, null, null, 0);
Hence, the output is coming like that.
I think you want the values in your add method (not sure what that method is for?) to be printed.
So, you need to call your constructor with those values.
Book book = new Book(1, "title", "de", 2);
book.view();
You can print all Book objects by storing the objects in an array and then iterating through the array and call the list function for each Object of the array
Book[] bookArray=new book[n];
Add your objects to this array
Now iterating through the array you would be able to print all the objects
for(int i=0;i<n;i++) {
bookArray[i].view();
}
OK, so we had to create like a bookshelf and book objects with publisher, author, copyright date, etc. on a seperate file (basically creating an object for a driver class). I've redone this twice now this week and still get the same error. Perhaps someone could point me in the right direction? Maybe I'm missing something, I'm not sure. EDIT: the problem is: sorry I'm getting ready for work and going ahead of myself I have three: first the output is giving me: Book#15db9742 Book#6d06d69c then the book class for the year is red saying to convert from a string to an int so I do then it wants to go back the other way
public class Book {
private String title;
private String author;
private String publisher;
private int copyDate;
public Book(String bookTitle, String authorName, String publisherName, int bookYear){
title = bookTitle;
author = authorName;
publisher = publisherName;
copyDate = bookYear;
}
public Book(){
title = "book titler";
author = "author name";
publisher = "book publisher";
copyDate = "2014";
}
public String getTitle() {
return title;
}
public void setTitle(String bookTitle) {
title=bookTitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String authorName) {
author = authorName;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisherName) {
publisher = publisherName;
}
public int getCopyDate() {
return copyDate;
}
public void setCopyDate(int copyDate) {
this.copyDate = copyDate;
}
}
Here is the main class:
public class BookShelf {
public static void main(String[] args) {
int bookYear = 2014;
Book name1 = new Book("book\n", "something\n", "something else\n", bookYear);
Book name2 = new Book("anotherBook\n", "anotherSomething\n", "somethingElse^2\n", bookYear);
System.out.println(name1);
System.out.println(name2);
}
}
I entered arbitrary information so I can make sure it works before I go searching for a good book to enter the information for lol.
Thank you!
I think you need to override the toString() method so System.out.println() prints the information you want about a book object.
By default Object's toString() doesn't print any fields but instead:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
How to use the toString method in Java?
This method would go in the class (each class has it's own `toString() implementation)
class Book{
...
#Override
public String toString(){
//feel free to change this sting to whatever you want
return "Book " + title;
}
}
Also as Andreas Jabusch in the other answer, your constructor sets copyDate incorrectly. It should be an int
copyDate = 2014
Get rid of the quotes which makes it a String.
Your
copyDate = "2014"
has to be
copyDate = 2014
it's an int, not a String.
I am currently working on an inventory program involving a one dimensional array, 2 classes (Store and Book), and several other things such as methods and a constructor.
The Store class which is the main class I guess you could say is supposed to include the main() method, and is supposed to read a list of purchases from a file, process each purchase with an appropriate message (ISBN number, amount, price, or problem (such as out of stock or do not have)), store an array of up to 15 books of type Book, a method to read in the inventory file, method to process a purchase, a method to print the inventory at closing along with the number of books sold and amount made at closing.
The Book class includes, book objects (each book object holds ISBN String, price double, and copies int), constructor, getters and setters, and a method to print the information.
Since the array is supposed to be created in the Store class, but be of type Book and made up of the book objects (I'm assuming?), I'm having trouble figuring out how to do this properly (assigning values to the isbn, price, copies variables, setting up the constructor correctly, etc).
Update
The main issue I'm having right now is being able to print the book object from my printInfo method. I am getting an error message at the print statement of that method stating "cannot find symbol. symbol: book". I can't really see if the program is actually working yet since that's kind of what I need to see at this point (the printed out book object) before I start adding in a few more methods to do other things that depend on this book object being correct.
Here is the code I have come up with so far:
The Store class:
import java.util.Scanner;
import java.io.*;
public class Store {
public static void main(String[] args) throws Exception {
Book[] books = readInventory();
for (Book : books) {
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
}
public static Book[] readInventory() throws Exception {
Book[] books = new Book[15];
java.io.File file = new java.io.File("../instr/prog4.dat");
Scanner fin = new Scanner(file);
String isbn;
double price;
int copies;
while (fin.hasNext()) {
for(int i = 0; i < books.length; i++) {
isbn = fin.next();
price = fin.nextDouble();
copies = fin.nextInt();
Book book = new Book(isbn, price, copies);
books[i] = book;
}
}
fin.close();
return books;
}
public static void printInfo(Book[] books) {
System.out.println(book);
}
}
And here is my Books Class:
public class Book {
private String isbn;
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) {
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
public String getISBN() {
return isbn;
}
public double getPrice() {
return price;
}
public int getCopies() {
return copies;
}
public void setISBN(String isbn) {
this.isbn = isbn;
}
public void setPrice(double price) {
this.price = price;
}
public void setCopies(int copies) {
this.copies = copies;
}
#Override
public String toString() {
return String.format("ISBN: %s, Price: %f, Copies: %d%n",
this.getISBN(), this.getPrice(), this.getCopies());
}
}
This is my first time working with classes, or at least creating multiple classes in the same program, so I'm still trying to figure out how this works. I've been reading a tutorial I found online that has been somewhat helpful, but I'm having trouble applying it to this specific type of program.
Any suggestions would be greatly appreciated.
Hi glad to see you've made the effort to actually try something before jumping on here. What you have done is pretty good so far. But what you really need now is a getter and setter method in your class Book. These will allow you to return or set the value of the variable for the object.
public class Book {
private String isbn;
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) { // Constructor?
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
public String getISBN() {
return this.isbn;
}
public double getPrice() {
return this.price;
}
public int getCopies() {
return this.copies;
}
public void setISBN(String value) {
this.isbn = value;
}
public void setPrice(double value) {
this.price = value;
}
public void setCopies(int value) {
this.copies = value;
}
}
This should help you get on the right track. Depending on how you want the information to come up would depend on whether you add System.out.println("ISBN: " + this.isbn); and so on in each get function, or you could declare a separate function getInfo which simply prints each. Or if you were returning it into store you could always print it that way. One more thing to note is that you have been declaring books as Book[] books = new Book[15] as you are creating an array of Book objects and not strings. If you need any more help let me know.
1.you shouldn't use String Array.you should declare Book Array instead. then It will be easier to assign your Book object.
for example
Book[] books = new Book[15];
books[i] = new Book(isbnNum,priceOfBook,copiesInStock);
2.because variable in Book class was declare in private type. you should create get methods in your Book class to get variable in any object.
for example
public String getbnNum()
{
return isbn;
}
public double getprice(){
return price;
}
public int getcopies(){
return copies;
}
I wrote comments in the code for you. I have to assume your file-reading code is correct since I don't have the file.
import java.util.Scanner;
public class Store {
/*
* This is the main method. It is where the code that starts off the
* application should go.
*/
public static void main(String[] args) throws Exception {
// Here, we take the array returned by the method and set it to a local variable.
Book[] books = readInventory();
// This is an alternative notation than a normal for-loop.
for (Book book : books) {
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
/* Alternative to above.
for (int i = 0; i < books.length; i++) {
Book book = books[i];
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
*/
}
// We add the return type of Book[] so we can get a reference to our array.
public static Book[] readInventory() throws Exception {
Book[] books = new Book[15];
java.io.File file = new java.io.File("../instr/prog4.dat");
Scanner fin = new Scanner(file);
// These variables don't need to be initialized yet.
String isbn;
double price;
int copies;
while (fin.hasNext()) {
// Fill the books array with Book objects it creates from the file.
for (int i = 0; i < books.length; i++) {
isbn = fin.next();
price = fin.nextDouble();
copies = fin.nextInt();
Book book = new Book(isbn, price, copies);
books[i] = book;
}
}
fin.close();
return books;
}
}
Book class:
public class Book {
private String isbn;
/*
* Careful using double as your type for variables that hold money values.
* If you do any division, you can end up getting answers different than
* what you might expect due to the way Java handles remainders. For that,
* make price a Currency type, which you can import from Java.util
*/
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) {
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
// This is an example of a getter method, which we need since our isbn is
// declared as private. Now, other methods can still read what isbn is.
public String getISBN() {
return isbn;
}
public double getPrice() {
return price;
}
public int getCopies() {
return copies;
}
/*
* We can use the "this" keyword to refer to this instance's isbn variable,
* instead of the local variable isbn that was passed to the method.
* Therefore, in this tricky notation we are setting the object's isbn
* variable to the isbn variable passed to the method.
*/
public void setISBN(String isbn) {
this.isbn = isbn;
}
public void setPrice(Double price) {
this.price = price;
}
public void setCopies(int copies) {
this.copies = copies;
}
}
Also note that a more advanced way to print the information for each book would be to make a toString() method in the Book class which overrides the default toString method it inherits from the generic Object class. You should use a special convention called an override annotation to do this as it is considered good practice when we redefine methods from a superclass (Object is a superclass of all objects, including Book).
#Override
public String toString() {
return String.format("ISBN: %s, Price: %f, Copies: %d%n",
this.getISBN(), this.getPrice(), this.getCopies());
}
That would allow us to simply call System.out.println(book);, for example, and would also mean we wouldn't have to rewrite all of this code every place we want to print a book. This is an important principle with objects—they generally should take care of themselves.
I am trying to print the first element on the two arrays in my Athlete class, country and name. I also need to create a object that simulates three dive attemps an athlete had (that is initially set to zero). I am new to OOP and I dont know how to go abouts doing this in my main... as far as constructors go. This is what i have done so far...
this is the main:
import java.util.Random;
import java.util.List;
public class Assignment1 {
public static void main(String[] args) {
Athlete art = new Athlete(name[0], country[0], performance[0]);
}
}
I just really am not sure what to do...
And this is the class with the arrays.
import java.util.Random;
import java.util.List;
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
//Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.)
Athlete(String[] name, String[] country, Performance[] performance) {
this.name = name;
this.country=country;
this.performance=performance;
}
public Performance Perform(Dive dive){
dive.getDiveName();
return null;
}
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String[] getCountry() {
return country;
}
public void setCountry(String[] country) {
this.country = country;
}
}
thanks in advance for any help and input!
btw there is other classes too, just not relevant atm..
First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.
However, if you really want to use that Getter and Setter, change the public modifier to private instead.
Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");
Variable name will be equal to "theolc".
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
Your attempt at an athlete class seems to be dealing with a group of athletes, which is a design fault.
Define a class to represent a single athlete, with fields that represent the athlete's attributes:
public class Athlete {
private final String name;
private final String country;
private List<Performance> performances = new ArrayList<Performance>();
// other fields as required
public Athlete (String name, String country) {
this.name = name;
this.country = country;
}
// getters omitted
public List<Performance> getPerformances() {
return performances;
}
public Performance perform(Dive dive) {
// not sure what your intention is here, but something like this:
Performance p = new Performance(dive, this);
// add new performance to list
performances.add(p);
return p;
}
}
Then your main method would use ti like this:
public class Assignment1 {
public static void main(String[] args) {
String[] name = {"Art", "Dan", "Jen"};
String[] country = {"Canada", "Germant", "USA"};
Dive[] dive = new Dive[]{new Dive("somersault"), new Dive("foo"), new Dive("bar")};
for (int i = 0; i < name.length; i++) {
Athlete athlete = new Athlete(name[i], country[i]);
Performance performance = athlete.perform(dive[i]);
// do something with athlete and/or performance
}
}
}
I think you are a little messed up with what you doing.
Athlete is an object, athlete has a name, i has a city where he lives.
Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
public static void main(String[] args) {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
// initialize your performance array here too.
//Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
Athlete art = new Athlete(name, country, performance);
}
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
#Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.