What I'am trying to do with this program is output the information of a song using the toString on Song class. When I output it, everything is fine except the SongType/genre. It is still outputting UNDETERMINED.
abstract class Song implements ISong //SONG CLASS
{
private String name;
private String rating;
private int id;
private SongType genre;
public Song()
{
name = " ";
rating = " ";
id = 0;
genre = SongType.UNDETERMINED;
}
public Song(String name, String rating, int id)
{
this.name = name;
this.rating = rating;
this.id = id;
this.genre =Song.UNDETERMINED;
}
public void setName(String name)
{
this.name = name;
}
public void setRating(String rating)
{
this.rating = rating;
}
public void setID(int id)
{
this.id = id;
}
public String getName()
{
return(this.name);
}
public String getRating()
{
return(this.rating);
}
public int getID()
{
return(this.id);
}
#Override
public String toString()
{
return("Song: " + this.name +
"\nID: " + this.id +
"\nRating: " + this.rating +
"\nGenre: " + this.genre);
}
}
class Pop extends Song //POP CLASS
{
public Pop(String name, String rating, int id)
{
super(name, rating, id);
}
}
interface ISong //INTERFACE
{
public enum SongType {POP, COUNTRY, HIPHOP, SOUL, UNDETERMINED;}
}
public class test{
public static void main(String [] args)
{
Song one = new Pop("Pop Song", "Five", 123);
System.out.println(one);
}
}
When I output it, everything is fine except the SongType/genre. It is still outputting UNDETERMINED.
But where do you actually set your genre field to anything but SongType.UNDETERMINED?
I suggest that you give the Song class and ISong interface a public SongType getGenre() method that returns the current genre, as well as an appropriate setter method, public void setGenre(SongType genre) and constructors that accept a SongType genre parameter if need be. The toString() method should call the getGenre() method to get the current genre state.
Most important, you will need to set the genre in a concrete class to something other than SongType.UNDETERMINED before trying to print it out.
Related
this is main method
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
now i created 2nd class authoer with getter and setter
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
noow i created new class Book
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
when i run this program the output give the memory adress ho can i print theese detail
You need to override toString() method in the class Author.
For example:
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
When you pass as argument of the method System.out.println() name of variable, method toString() of the class of that variable is being called. If you don't override that method in class Author or Book, toString() method inherited by these classes from Object class is being called (all classes in Java inherit from Object class). By default, this method prints address in memory for classes with toString() not defined in their bodies. There is a simple example, how you can override it in Author method:
class Author {
#Override
public String toString() {
return "Author name: " + this.name + "\nAuthor email: " + this.email + "\nAuthor gender : " + this.gender;
}
To print contents of an array (in your example to print each Author contained in Author[] authors) you might want to use one of these way to achieve that (as Author[] or Book[] is actually a type of array and not a type of Book or Author and has its own toString() method printing address in memory) :
Create a loop iterating over each element of authors array:
for (Author author : authors) {
System.out.println(author + "------"); // toString() method of each Author is called and added simple separator
}
Call Arrays.toString(authors) method. Class Arrays is provided to let you manipulate arrays in many different ways. You can read about this class in Java API documentation. This is a part of what documentation says about Arrays.toString() method:
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
package oops;
public class Main {
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
}
}
package oops;
public class Author {
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return name+ " " +email+ " " +gender+ " ";
}
package oops;
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String getName() {
return name;
}
/*public Author[] getAuthor() {
return author;
} */
public Author[] getAuther() {
for (int i=0;i<=author.length;i++);
return author;
}
public String toString() {
return name+" "+author+" "+price+" "+qty+" ";
}
public Author[] getAutherNames() {
for (int i=0;i<=author.length;i++);
return author;
}
}
this is my full program
You an override toString() or you can print the attributes of the object directly as follows:
Book b = new Book(/*args*/);
System.out.println("Name: " + b.name);
// continue printing all the attributes in the same way
You can try this instead of overriding toString() method in the object class.
Hope this helps...
I am working on a project that links books to their authors.The author info is part of the book class and it is an Author object in the book class and its data will become part of the book class. I have the author class:
public class Author {
private String Name;
private String email;
private char gender;
public Author( ) {
Name="Emily";
email="email#email.com";
gender='f';
}
public String getName (){
return Name;
}
public void setName (String Name){
this.Name=Name;
}
public String getEmail (){
return email;
}
public void setEmail(String email){
this.email=email;
}
public char getGender (){
return gender;
}
public void setGender(char gender){
this.gender=gender;
}
public String toString () {
String x = "Name: " + Name + "email " + "gender: " + gender;
return x;
}
}
and the book class:
public class Book {
private String name;
private Author author;
private double price;
private int quantity;
public Book (){
name="Book Name";
author=Author.toString();
price=11.79;
quantity=2;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Author getAuthor(){
return author;
}
public void setAuthor () {
this.author=author;
}
public double getPrice () {
return price;
}
public void setPrice (double price) {
this.price=price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity (int quantity) {
this.quantity=quantity;
}
public String toString (){
String x = "Book is " + name + "Author and author info "+ author + "Price " + price + "Quantity " + quantity;
return x;
}
}
I need to store the contents of the toString() method in the Author variable in the book class as the author info. How do I do this?
You don't need to store the value of the toString() method of the Author class, this would couple your classes unnecessarily and break one of the core principals of good OO design.
The toString method of the Author class should be responsible for presenting a sensible String representation of its state (which it seems to). Your book class should do the same, delegating to classes it interacts with to do the same:
public String toString() {
return "Book is " + name + "Author and author info "+ author.toString() + "Price " + price + "Quantity " + quantity;
}
As noted in the comments, you're already doing this in the code snippet posted in the question, your question implies that this this may have not been 'by design'. I would recommend researching Object Encapsulation and delegation.
As part of an assignment I am having to produce a LinkedList class called Registry. It is intended to be part of a simple student registration system with an interface.
Unfortately, I have literally hit a wall and have no idea on what to do next with what I am doing here. The Registry class is just intended to manage a linked list of students called studentList.
Below is the current, rather incomplete class I have made so far.
import java.util.*;
public class Registry
{
LinkedList<Student> studentList;
public Registry()
{
}
public void addStudent(Student aStudent)
{
studentList.add(aStudent);
}
public void deleteStudent(int studentID)
{
studentList.remove(studentID);
}
#Override
public String toString()
{
return getClass().getName() +
}
public String format()
{
System.out.format(studentList);
}
}
Now, my main worry is using Student. As part of the assignment, I have had to make another class called Student which create instances of Students, containing forenames, surnames, Student IDs and degree Schemes as strings.
How will I be able to use that sperate class to be added to the LinkedList instanted in Registry? And how can I get the Registry class to fully function?
I will try and provide any additional details on request. I am likely unclear, so if I am, let me know, and I will try and explain as best I can.
EDIT: This is the Student Class as requested:
public class Student
{
private String foreName;
private String surName;
private String studentID;
private String degreeScheme;
public Student()
{
}
public void setForeName(String foreName)
{
this.foreName = foreName;
}
public String getForeName()
{
return foreName;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public String getSurName()
{
return surName;
}
public void setStudentID(String studentID)
{
this.studentID = studentID;
}
public String getStudentID()
{
return studentID;
}
public void setDegreeScheme(String degreeScheme)
{
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme()
{
return degreeScheme;
}
#Override
public String toString()
{
return getClass().getName() + "[foreName = " + foreName + " surName "
+ surName + " studentID " + studentID + " degreeScheme "
+ degreeScheme + "]";
}
public void format()
{
System.out.format("%5s%20s%11s%20s", foreName, surName, studentID, degreeScheme);
}
}
import java.util.Iterator;
import java.util.LinkedList;
public class Tester {
public static void main(String[] args) {
Registry r = new Registry();
r.addStudent(new Student("13", "John", "Doe", "Physics")); // Add a student to the Registry
r.addStudent(new Student("212", "Jane", "Bow", "Chem")); // Add another Student
System.out.println(r); // Print the Student List
r.deleteStudent(212); // Deletes student with ID 212
System.out.println(r);
}
}
class Student {
private String studentID;
private String foreName;
private String surName;
private String degreeScheme;
public Student(String studentId, String foreName, String surName, String degreeScheme) {
this.studentID = studentId;
this.foreName = foreName;
this.surName = surName;
this.degreeScheme = degreeScheme;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
public String getForeName() {
return foreName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getStudentID() {
return studentID;
}
public void setDegreeScheme(String degreeScheme) {
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme() {
return degreeScheme;
}
#Override
public String toString() {
return getClass().getName() + "[foreName = " + foreName + " surName " + surName + " studentID "
+ studentID + " degreeScheme " + degreeScheme + "]";
}
public void format() {
System.out.format("%5s%20s%11s%20s", foreName, surName, studentID, degreeScheme);
}
}
class Registry {
LinkedList<Student> studentList;
public Registry() { // Creates studentList
studentList = new LinkedList<>();
}
public void addStudent(Student aStudent) {
studentList.add(aStudent);
}
public void deleteStudent(int studentID) {
int index = searchList(studentID); // Gets index of the student in the Registry
if (index == -1)
throw new IllegalArgumentException("Student not found");
// Since studentList is implemented as LinkedList, .remove removes element at specified position
studentList.remove(index);
}
// Search by studentID , if found, return position in the list
private int searchList(int studentID) {
Iterator<Student> it = studentList.iterator();
int count = -1;
while (it.hasNext()) {
count++;
Student temp;
temp = it.next();
if (Integer.parseInt(temp.getStudentID()) == studentID) {
return count;
}
}
return -1;
}
#Override
//Suggestions to improve the toString are welcome
public String toString() {
for (Student student : studentList) {
student.format();
System.out.println();
}
return "";
}
}
In any data structure there are three functions that almost always require implementation:
Insertion
Searching
Deletion
Let me begin by clarifying what the general Linked List structure consists of.
The linked list works by operating on nodes. Each node contains the actual data you want to store/modify/access.
Registry: This should be responsible for maintaining the structure and providing a way of inserting/searching for/deleting specific nodes in the list.
Student: Stores the data and controls how it is accessed and modified
So far, you have your Registry framework created appropriately. (Although you will want to implement a search method.)
For your student class, you simply create the member variables of the class that you need, as well as the appropriate getters/setters for them.
public class Student {
private String id;
private String forename;
private String surname;
private String degreeScheme;
private Student next; // Maintains a reference to the next node in the list
Student () {
//Default constructor values
}
Student (String id, String forename, String surname, String degreeScheme, Student next) {
this.id = id;
this.forename = forename;
this.surname = surname;
this.degreeScheme = degreeScheme;
this.next = next;
}
public void setID (String id) {
this.id = id;
}
public String getID () {
return id;
}
public void setforename (String forename) {
this.forename = forename;
}
public String getforename () {
return forename;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname () {
return surname;
}
public void setDegreeScheme(String degreeScheme) {
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme () {
return degreeScheme;
}
public void setNext (Student next) {
this.next = next;
}
public Student getNext () {
return next;
}
} //End Student Class
This should be a good base to get you started. Remember, when creating data structures you'll avoid a lot of headaches by making sure that you have a clear separation of concerns. Make the student class purely responsible for storing and maintaining the data, and let the Registry class be responsible for maintaining the structure itself!
At this point, you can utilize the Student class within your Registry class, just insert the nodes as you want, search for them, delete them as needed.
this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)
I get such a JSON from the server and want to parse it to my objects:
"product":{
"product_type":"assignment",
"id":717,
"product_profile":{
"title":"new Order from java",
"info":"Some special info",
"dtl_expl":true,
"special_info":""
}
}
Depend on "product_type" value I get different value of "product_profile" from server. The "product_profile" can be one of three types. I created class presentation for each of them. But question is that how organize correct parsing of JSON object to my Product class due to OOP principles? Should I create interface and implement it in each of my three classes, or I should create one parent class and extend it in my three classes to make it work right?
My classes structure. First of all Product class , object of which I should get as a result from json:
public class Product {
ProductAssignment prodAss;
ProductWriting prodWr;
ProductType returnState;
#SerializedName("id")
int id;
#SerializedName("product_type")
String product_type;
#SerializedName("product_profile")
ProductType product_profile;
public Product()
{}
public Product(int id, String product_type, ProductType product_profile)
{
this.id = id;
this.product_type = product_type;
this.product_profile = product_profile.returnObject(product_type);
}
public int getProductId()
{
return this.id;
}
public String getProductType()
{
return this.product_type;
}
public ProductType getProduct()
{
return product_profile.returnObject(product_type);
}
public void setProductId(int id)
{
this.id = id;
}
public void setProductTitle(String product_type)
{
this.product_type = product_type;
}
public void setProduct(ProductType product_profile)
{
this.product_profile = product_profile;
}
#Override
public String toString() {
return "id=" + id + " " + "title=" + product_type
+ " " + "profile=" + product_profile + "}";
}
}
Now parent class ProductType for two subclasses:
public class ProductType extends ProductType{
String product;
static ProductType productType;
static ProductAssignment productAssignment;
static ProductWriting productWriting;
IProductType component;
private ProductType returnState;
ProductAssignment prodAss;
ProductWriting prodWr;
public ProductType()
{
}
public ProductType(IProductType c)
{
component = c;
}
// implemented method of interface
#Override
public ProductType returnObject(String product_type)
{
System.out.println("ProductType");
if (product_type.equals("assignment"))
returnState = prodAss.returnObject(product_type);
else if (product_type.equals("writing"))
returnState = prodWr.returnObject(product_type);
System.out.println(returnState.getClass().getName());
return returnState;
}
}
One of the subclasses:
public class ProductWriting extends ProductType{
#SerializedName("id")
int id;
#SerializedName("title")
String title;
#SerializedName("pages_number")
int pages_number;
#SerializedName("number_of_references")
String number_of_references;
#SerializedName("dtl_expl")
boolean dtl_expl;
#SerializedName("info")
String info;
public ProductWriting()
{}
public ProductWriting(String title, String info, boolean dtl_expl,
int pages_number ,
int id,String number_of_references)
{
this.title = title;
this.info = info ;
this.dtl_expl = dtl_expl;
this.id = id;
this.pages_number = pages_number;
this.number_of_references = number_of_references;
}
public ProductWriting(IProductType c){
super(c);
}
// getters and setters
#Override
public ProductType returnObject(String res) {
System.out.println("Writing");
super.returnObject(res);
return new ProductWriting();
}
}
Another one :
public class ProductAssignment extends ProductType{
ProductAssignment thisObj;
#SerializedName("title")
String title;
#SerializedName("info")
String info;
#SerializedName("dtl_expl")
boolean dtl_expl;
#SerializedName("special_info")
String special_info;
#SerializedName("shoot_exclusive_video")
boolean shoot_exclusive_video;
#SerializedName("shoot_common_video")
boolean shoot_common_video;
public ProductAssignment()
{}
public ProductAssignment(String title, String info, boolean dtl_expl, String special_info,
boolean shoot_common_video, boolean shoot_exclusive_video)
{
this.title = title;
this.info = info ;
this.dtl_expl = dtl_expl;
this.special_info = special_info;
this.shoot_common_video = shoot_common_video;
this.shoot_exclusive_video =shoot_exclusive_video;
}
// getters and setters
#Override
public ProductType returnObject(String res) {
System.out.println("Assignment");
super.returnObject(res);
return new ProductAssignment();
}
#Override
public String toString()
{
return "title=" + title + "info " + "=" + info
+ " " + "profile=" + dtl_expl + "}";
}
}
Interface for binding my classes:
public interface IProductType
{
ProductType returnObject(String parse);
}
I tried to implement in this way, but it doesn't work for now with it.