How would I use an array list of type Customer(Which has 2 child classes, nonmember and member) to print out all customer objects using a comparison? in other words, I want to check the array list at a certain index and check if it is a Non-member or member object and print output accordingly. here is my code:
ArrayList<Customer> customerList = new ArrayList<Customer>();
for(int i = 0; i < customerList.size(); i++)
{
if(customerList.get(i) == // nonmember)
{
// want to use toString in NonMemberCustomer class
}
else // member
{
// use toString in MemberCustomer class to print output.
}
}
public String toString()
{
return "\nMember Customer:" + super.toString() +
"Collected Points:\t" + pointsCollected + "\n\n";
}
public String toString()
{
return "NonMember Customer:" + super.toString() +
"Visit Fee:\t\t" + visitFee + "\n\n";
}
Declare your arraylist using Customer as the parametric type:
// So that the polymorphism would work
List<Customer> customerList = new ArrayList<>();
Second, you don't need an if/else statement to print the respective toString()s of your objects; just override the toString() method in each of your classes & polymorphism shall take it from there.
for(int i =0; i < customerList.size();i++) {
// Implicit call to the toString() method
System.out.println(customerList.get(i));
}
The classes: (e.g)
class Customer {
// properties & methods
#Override
public String toString() {
System.out.println("The customer's toString !");
}
}
class Member extends Customer {
// properties & methods
#Override
public String toString() {
System.out.println("The member's toString !");
}
}
class NonMember extends Customer {
// properties & methods
#Override
public String toString() {
System.out.println("The nonmember's toString !");
}
}
Related
I'm making a solar system model that uses takes different solar systems and sets of planets through the use of classes. I've chosen to use an arraylist to store each object of a planet within the solar system although am now struggling to output the data in a suitable format.
The format i am looking for in the toString() method is 'Planet X has a mass of A Earths, is BAU from its star, and orbits in C years: could be habitable? D'
I have attempted using for loops to print each planet however don't believe this is the correct way as a return will cause the loop to stop. Many thanks
SolarSystem.java
import java.util.ArrayList;
public class SolarSystem {
private String systemName;
private double systemLuminosity;
public SolarSystem(String name, double luminosity) {
this.systemName = name;
this.systemLuminosity = luminosity;
}
ArrayList<Planet> list = new ArrayList<>();
public void addPlanet(String name, double mass, double distance) {
list.add(new Planet(name, mass, distance, systemLuminosity));
}
public void planetProperties() {
}
public String toString() {
System.out.println(list.size());
String results = "+";
for (Planet planet : list) {
results += planet.getName(); //if you implement toString() for Dog then it will be added here
}
return results;
}
}
Planet.java
public class Planet {
private String planetName;
private double planetMass;
private double distanceFromStar;
private double orbitalPeriod;
private String isHabitable;
public Planet(String name, double mass, double distance, double systemLuminosity) {
setName(name);
setMass(mass);
setDistanceFromSun(distance);
setOrbitalPeriod(distance);
setIsHabitable(mass, distance, systemLuminosity);
}
public void setName(String name) {
planetName = name;
}
public String getName() {
return planetName;
}
public void setMass(double mass) {
planetMass = mass;
}
public double getMass() {
return planetMass;
}
public void setDistanceFromSun(double distance) {
distanceFromStar = distance;
}
public double getDistanceFromStar() {
return distanceFromStar;
}
public void setOrbitalPeriod(double distance) {
orbitalPeriod = Math.sqrt(distance*distance*distance);
}
public double getOrbitalPeriod() {
return orbitalPeriod;
}
public void setIsHabitable(double mass, double distance, double luminosity) {
if (mass >= 0.6 && mass <= 7.0) {
if ((distance >= 0.75 * Math.sqrt(luminosity)) && (distance <= 2.0 * Math.sqrt(luminosity))) {
isHabitable = "yes";
} else {
isHabitable = "no";
}
} else {
isHabitable = "no";
}
}
public String getIsHabitable() {
return isHabitable;
}
}
Main.java
public class Main {
public static void main(String[] args) {
//Create our solar system
SolarSystem ourSystem = new SolarSystem("Our System",1.0);
//Add planets in our solar system
ourSystem.addPlanet("Mercury", 0.055, 0.387);
ourSystem.addPlanet("Venus", 0.815, 0.723);
ourSystem.addPlanet("Earth", 1.0, 1.0);
ourSystem.addPlanet("Mars", 0.107, 1.52);
ourSystem.addPlanet("Jupiter", 317.8, 5.20);
ourSystem.addPlanet("Saturn", 95.2, 9.58);
ourSystem.addPlanet("Uranus", 14.5, 19.20);
ourSystem.addPlanet("Neptune", 17.1, 30.05);
System.out.println(ourSystem.toString());
}
}
You need to implement a toString() method inside your Planet class, for example:
class Planet {
private String planetName;
private double planetMass;
private double distanceFromStar;
private double orbitalPeriod;
private String isHabitable;
#Override
public String toString() {
return String.format(
"Planet %s has a mass of %f Earths, is %f from its star, and orbits in %f years: could be habitable? %s%n",
this.planetName, this.planetMass, this.distanceFromStar, this.orbitalPeriod, this.isHabitable);
}
}
Then inside your SolarSystem class you can create a list with something like this, you already have that part almost correct but I've changed getName to toString:
#Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (Planet planet : list) {
buf.append(planet);
}
return buf.toString();
}
If you want to print out a description for the entire solar system (the entire array list of planets), I would suggest to implement the toString() method inside the Planet class. Doing so will allow you to simply iterate over the Planets array list, and just call planet.toString(). Encapsulating the logic for a singular planet inside the Planet class is the way to go.
You have to redefine toString in the Planet class and replace the toString of SolarSystem to use it.
public class Planet {
...
public String toString() {
return "Planet " + planetName + " has a mass of " + planetMass +
" Earths, is BAU from its star, and orbits in " + orbitalPeriod +
" years: could be habitable? " + isHabitable;
}
}
public class SolarSystem {
...
public String toString() {
String results = "";
for (Planet planet : list) {
results += planet.toString() + "\n"; // Use the toString of planet and add a new line
}
return results;
}
}
Note: for performance reasons as commented by oleg it is preferable to use a StringBuilder to concatenate strings. In this situation where you have few items and the problem is not related to the performances you can leave the + operator.
Growing your java knowledge you will find useful functions like String.join:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
That will help you mantaining your code simpler and cleaner replacing this:
public String toString() {
String results = "";
for (Planet planet : list) {
results += planet.toString() + "\n"; // Use the toString of planet and add a new line
}
return results;
}
with
public String toString() {
return String.join("\n", list);
}
but my tip is to start from the basis of java before trying to use more advanced functions. Otherwise you will use them without knowing what happens behind the scenes
To echo other posters, you need to define a custom toString() method in the planet class first. Please see my suggestions below. They are presented as pseudo-code typed on the fly, not actual code (for there might be a few things here and there that might not compile.)
But the pseudo-code should give an idea for a possible solution. Hit me up if you still have questions.
Based on your requirements:
The format i am looking for in the toString() method is 'Planet X has
a mass of A Earths, is BAU from its star, and orbits in C years: could
be habitable? D'
Your Planet.toString method could look as follows (this is pseudo-code, not bound to be compilable, but you get the gist of it.)
public class Planet {
/* your class as it is, with the
* addition of a possible toString
* implementation */
public String toString(){
return String.format(
"Planet: %s, " +
"mass: %f, " +
"distance: %f, " +
"orbital period: %f, " +
"habitable: %b"
this.getName(),
this.getMass(),
this.getDistanceFromStar(),
this.getOrbitalPeriod(),
this.getIsHabitable());
}
}
Then, your SolarSystem class should have an appropriate toString method that loops over the collection of planets in it. Your original toString method had the right idea, I'm just extending the notion.
public class SolarSystem {
/*
Your solar system class plus some changes
...
*/
public String getName(){
return this.systemName;
}
public String getLuminosity(){
return this.systemLuminosity;
}
public int getPlanetCount(){
return this.list.size();
}
public String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(
String.format("System: %s\nLuminosity: %f\nPlanet Count:%d\n",
this.getName(),
this.getLuminosity(),
this.getPlanetCount()
)
);
for (final Planet planet : list) {
buffer.append('\t')
.append(planet.getString())
.append('\n');
}
return buffer.toString();
}
}
Now, I'm a bit confused with this:
I have attempted using for loops to print each planet however don't
believe this is the correct way as a return will cause the loop to
stop. Many thanks
A return statement will stop a loop if the return is done within the loop.
A return statement done within a function called within the loop will not end the loop.
That is, a return only ends the function that makes the return call, not functions up in the call chain.
Compare this
for(Foo f : fooList){
if(something){
return; // this will stop the loop
}
}
With this
for(Foo f : fooList){
if(something){
callThisFu(); // the return within callThisFu *will not* exit the loop
}
}
Hope this clear this up.
I seem to have a problem with a subtask. It's in danish so I put in the translated version of it:
Create a class Field, that is representing the fields of a monopoly game. Initially, Field can contain these encapsulated variables:
String name - short name of the field
int number - a number in the range[1..40]
Both variables must be initialized in a constructor, and there must only be getters, as they never will be changed after creation.
Moreover, there should be a method with the signature public String toString(), so it's easy to print what Field a player has landed on.
At first it's allowed to just call the fields Field1, Field2...
My Field class look like this:
public class Field {
String name;
int number;
public Field(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}
In my main method I wanted to test this. So I wrote the following:
Field[] board = new Field[40]; // a board containing 40 fields
for (int i = 0; i < board.length; i++) {
board[i] = new Field("Field" + (i + 1), i + 1);
}
System.out.println("Board: " + Arrays.toString(board));
In my console I get this:
Board: [test.Field#2a139a55, test.Field#15db9742, test.Field#6d06d69c,......]
And I want this:
Board: [Field1, Field2, Field3,......]
Override Field's toString() to return the name, i.e.
public String toString() {
return name;
}
What you get (e.g. test.Field#2a139a55) is the default implementation of toString() which can be found in Object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
You missed the
Moreover, there should be a method with the signatur public String toString(),
part of your task.
Are you able to use java8? Then I would suggest this:
Field[] board = new Field[40]; // a board containing 40 fields
for(int i = 0; i < board.length; i++){
board[i] = new Field("Field" + (i + 1), i + 1);
}
String commaSeparatedName =
Arrays.stream(board) // all items as stream
.map(Field::getName) // for each take its name
.collect(Collectors.joining(", "); // join names with a comma
System.out.println("Board: [" + commaSeparatedNames +"]");
I am attempting to print out a hashset taking in records from a database which are currently stored in two seperate ArrayLists. When I attempt to print out the HashSet the following error shows.
This is your HashSet[nyu.Sorting#378bf509, nyu.Sorting#7b23ec81, nyu.Sorting#15aeb7ab, nyu.Sorting#27d6c5e0, nyu.Sorting#7ef20235, nyu.Sorting#4f3f5b24, nyu.Sorting#6acbcfc0, nyu.Sorting#2d98a335, nyu.Sorting#5fd0d5ae, nyu.Sorting#16b98e56]
And this is my code:
public static HashSet<Sorting> t() {
Sorting s = new Sorting();
int TimeNeededOne = 75;
int TimeNeededTwo = 75;
int assignedTimeOne = 0;
int assignedTimeTwo = 0;
HashSet<Sorting> c = new HashSet<Sorting>();
for(int i=0; i<=i1.size()-1; i++)
{
if((assignedTimeOne < TimeNeededOne) && !(assignedTimeOne+ i1.get(i).getLengthMins() > offensiveTimeInMins) )
{
c.add(i1.get(i));
assignedTimeOne += i1.get(i).getLengthMins();
}
}
for(int i=0; i<=i2.size()-1; i++)
{
if((assignedTimeTwo < TimeNeededTwo) && !(assignedTimeTwo + i2.get(i).getLengthMins() > TimeNeededTwo) )
{
c.add(i2.get(i));
assignedTimeTwo += i2.get(i).getLengthMins();
}
}
System.out.println("Training programme :" + c.size());
System.out.println("This is your training programme" + c.toString());
return c;
}
The c.size is there to confirm that ten entries are made which is correct however the formatting of the records from the hashset obviously contains a problem. Any help with this issue would be greatly appreciated.
Thanks.
One way of doing this would be to override the toString() method of your Sorting class to print its contents:
public class Sorting {
...
#Override
public String toString() {
// Return a String that represents this object
return "...";
}
}
You need override toString() method in the Sorting class, for example:
class Sorting {
...
#Override
public String toString() {
// a string representation of Sorting object
}
}
java.util.Iterator runs through the whole collection and for each element invokes a toString() method. The data recorded in the java.lang.StringBuilder, which returns of its string representation at the end.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
Recently, I've learned something: I have no idea how to use toString methods.(If you've seen my last question, you'll get a prime example.)
Anyways, I was going through some unfinished programs of mine from an Intro to Java class I took last year and this one I just cannot finish. My effort to become a better programmer has faced the ultimate challenge: toString methods.
The basic overview is that I had to write a 'Grocery' store program where the ShoppingCart class was an ArrayList of Grocery Objects.
There's just one problem- when I run the program I get
Grocery.ShoppingCart#2eeb3c84
My old enemy, the toString() looks like it is required.
The output I should be getting is this:
[Tomatoes: 2.76 $1.39, Mac & Cheese: 6.0, $0.89]
now if I print out the Cart ArrayList (System.out.println(Cart)) I get this:
[Tomatoes, 2.76, $1.39, Mac & Cheese, 6.0, $0.89]
Exactly the output I should be getting.
How does this happen? How can I fix this?
When I print out the Cart Arraylist, I get the output I want (I still get the "Grocery.ShoppingCart#). I have to find some way to replace the "Grocery.ShoppingCart#[etc.]" with the ArrayList.
Anybody have any ideas?
Thanks!
-Chris
Bits of the ShoppingCart class:
ArrayList<Grocery> Cart = new ArrayList<Grocery>();
int size = Cart.size();
double tot = 0.0;
public ShoppingCart(){
}
...
public void printReceipt() {
Grocery temp = new Grocery();
double pr = 0.0;
double qu = 0.0;
String n = "";
String con = "IF YOU SEE ME SOMETHING IS WRONG!";
double gr = 0.0;
for(int k = 0; k < size; k++){
temp = Cart.get(k);
n = temp.getName();
qu = temp.getQuan();
pr = temp.getPrice();
tot = qu * pr;
con = n + ":" + " " + qu + ", " + pr + "\t\t Total: $" + tot;
}
System.out.println("====RECIEPT====");
System.out.println("Grand Total:\t" + "$" + totalPr());
}
Grocery Class Printing out ShoppingCart
public static void testShoppingCartClass ()
{
System.out.println ("Testing ShoppingCart class\n");
ShoppingCart myCart = new ShoppingCart();
System.out.println (" ShoppingCart using default constructor: ");
System.out.println ("\t" + myCart);
myCart.addItem (new Grocery("Tomatoes", 2.76, 1.39));
myCart.addItem (new Grocery("Mozzarella", 0.95, 4.59));
myCart.addItem (new Grocery("Mac & Cheese", 6, 0.89));
System.out.println ("\n ShoppingCart after adding three items: ");
System.out.println ("\t" + myCart);
myCart.removeItem (1);
System.out.println ("\n ShoppingCart after removing an item: ");
System.out.println ("\t" + myCart);
System.out.println ("\n\nPrinting receipt: \n");
myCart.printReceipt();
System.out.println ("\n\nDone testing ShoppingCart class\n\n");
}
You can override toString to return whatever you want. In your case, it looks like you want to do:
class ShoppingCart {
ArrayList<Grocery> cart;
...
#Override
public String toString() {
return cart.toString();
}
}
Java's default toString() method on any object will print out what you're seeing ("Grocery.ShoppingCart#[etc.]"). This is the Class with the object's hash code appended to the end of it.
From what I see in that output, you're calling .toString() on an instance of the ShoppingCart class which is why you're getting that output.
In order for that class to print out the contents of the ArrayList - Cart, which is a member of that class, you will need to override the toString() method of that class to print the contents of the ArrayList. Once it is overridden, your implementation of the toString() will be called rather than the default.
public String toString() {
// return the string that you want.
}
toString() is called on shoppingCart when you call System.out.println(shoppingCart) in order to retrieve the string to print.
Yes, you'll need a toString() on your ShoppingCart.
If I understand what you're trying to do though, may I suggest going with a more conventional Java bean approach? Here's a simplistic view.
Bean with getter and setters. A better name for this might be Item. You can change the types as needed as well.
public class Grocery {
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private BigDecimal quantity;
private BigDecimal price;
private String name;
#Override
public String toString() {
return "Grocery{" +
"quantity=" + quantity +
", price=" + price +
", name='" + name + '\'' +
'}';
}
}
And your cart:
public class ShoppingCart {
List<Grocery> contents;
public void initialize() {
contents = new ArrayList<Grocery>();
}
public void addItem(Grocery item) {
contents.add(item);
}
public void removeItem(Grocery item) {
boolean wasRemoved = contents.remove(item);
if (!wasRemoved) {
System.out.println("Item not found in cart: " + item);
}
}
public List<Grocery> getContents() {
return contents;
}
#Override
public String toString() {
return "ShoppingCart{" +
"contents=" + contents +
'}';
}
}
And some class to run it:
public class CartRun {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.initialize();
Grocery item = new Grocery();
item.setName("Tomatoes");
item.setPrice(BigDecimal.valueOf(2));
item.setQuantity(BigDecimal.valueOf(3));
cart.addItem(item);
System.out.println("Item="+item);
System.out.println("Cart="+cart);
}
}
Output:
Item=Grocery{quantity=3, price=2, name='Tomatoes'}
Cart=ShoppingCart{contents=[Grocery{quantity=3, price=2, name='Tomatoes'}]}
Also, stay away from capital letters (e.g., "Cart") for variable names because it looks like a static method call by convention.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is the toString() method being called when I print an object?
I have this piece of code below. I understand everything else except the output using the toString method in the Room Class . In the HotelMain Class, I just called the displayRooms Method that was in the Hotel Class. But, when I ran the program, the toString output was shown in the console.
If I'm right toString() is the textual representation of the value in the object. But, I'm not sure where I called the toString method.
Can someone solve my dilemma? Thank You.
Hotel Class
public class Hotel {
private String hotelName;
private Room[] rooms;
public Hotel(String hotelName, int numberOfRooms) {
this.hotelName = hotelName;
this.rooms = new Room[numberOfRooms];
}
public void addRooms(Room room) {
int position = -1;
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom == null) {
position = i;
break;
}
}
if (position != -1) {
rooms[position] = room;
System.out.println("New room added at postion " + position);
} else {
System.out.println("Addition of room failed.");
}
}
public void displayRooms() {
System.out.println("The Hotel: " + this.hotelName + " has the following rooms.");
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
}
}
Room Class
public class Room {
private int roomNumber;
private int numberOfBeds;
private boolean smokingOrNonSmoking;
public Room() {
}
public Room(int roomNumber, int numberOfBeds, boolean smokingOrNonSmoking) {
this.roomNumber = roomNumber;
this.numberOfBeds = numberOfBeds;
this.smokingOrNonSmoking = smokingOrNonSmoking;
}
#Override
public String toString() {
return "Room [roomNumber=" + roomNumber + ", numberOfBeds="
+ numberOfBeds + ", smokingOrNonSmoking=" + smokingOrNonSmoking
+ "]";
}
}
Hotel Main
public class HotelMain {
public static void main(String[] args) {
Hotel hotel = new Hotel("MahaRani Chain of Hotels", 10);
Room room1 = new Room(4, 2, true);
Room room2 = new Room(2, 1, false);
Room room3 = new Room(6, 3, true);
Room room4 = new Room(6, 4, false);
hotel.addRooms(room1);
hotel.addRooms(room3);
hotel.addRooms(room4);
hotel.addRooms(room2);
hotel.displayRooms();
}
}
Console
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
You have the above code in your displayRooms() method. It prints tempRoom, which is a reference of Room, and hence it calls toString() method overridden in the Room class.
when you call
System.out.println(tempRoom);
the toString() method of Room is automatically called on tempRoom.
In this line
System.out.println(tempRoom);
this is the same as
System.out.println(tempRoom.toString());
toString is a special method of the Object class, here is its description:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
This method is widely used in those places when an object should be converted to textual representation. When you print an object to PrintStream (System.out in this case), this stream calls toString to convert this object to a string.