Print Array of Objects in BlueJ [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment, I was asked to work on calling a class and creating an array objects, which i did here;
public void DVDArrayObjects() {
//creates variables
int i;
DVDClass[] dvdArray = new DVDClass[5];
//reference to DVDClass
for (i = 0; i < 2; i ++) {
//create new instance of calling the class
dvdArray[i] = new DVDClass();
//create new instance of getting the info
dvdArray[i].getDVDInfo();
//display
//System.out.println(dvdArray[i]);
}
}
Creating the array of objects works fine, but displaying doesn't. it shows the memory allocation when i run it. I'm really stuck as to how to get it to display.
** EDIT **
When i use System.out.println(dvdArray[i].getDVDInfo()); the error void types not allowed in here shows up
** END OF EDIT **
Any help at all would be greatly appreciated.

Print the DVD info (assuming that it returns a string).
System.out.println(dvdArray[i].getDVDInfo());
If it doesn't return a string, you need to override the toString() method on the class DVDInfo like this.
#Override
public String toString()
{
return "Film Name\t: " + filmName +
"\nFilm Director\t: " + filmDirector +
"\nRun Time\t: " + runTime +
"\nLead Actor\t: " + leadActor;
}
Hope this helps.

You need to override the toString() method.
public class DVDCLass {
#Override
public String toString(){
return // whatever you want the output to be
}
}

Override toString() method in your DVDClass class
do like below
class DVDClass{
public String toString(){
return // whatever you want the output to be
}
}

Related

Need assistance with question on java generics [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
My output is currently:
Avengers#15db9742 Avengers#6d06d69c
I need to figure out how to display the names as well, using the generic print method. I've been trying things like: GenericMethod_violette.<Avengers>print(avenger.getName()) and GenericMethod_violette.<Avengers>print(avenger.trueIdentity()) but after days on this I seem to be stuck.
My output needs to be:
Avengers#15db9742 Avengers#6d06d69c
Tony Stark, Bruce Banner
My GenericMethod_violette.java:
import java.io.ObjectInputStream.GetField;
public class GenericMethod_violette {
public static void main(String[] args ) {
Avengers[] avenger = { new Avengers("Tony Stark"), new Avengers("Bruce Banner")};
GenericMethod_violette.<Integer>print(integers);
GenericMethod_violette.<String>print(strings);
GenericMethod_violette.<Avengers>print(avenger);
}
public static <E> void print(E[] list) {
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
}
My Avengers.java:
public class Avengers
{
private String trueIdentity;
public Avengers(String name)
{
trueIdentity = name;
}
public String getName()
{
return trueIdentity;
}
public String sayTrueIdentity()
{
return "Hello, I'm " + trueIdentity + "!";
}
}
you can use write toString inside Avengers
public class Avengers
{
private String trueIdentity;
public Avengers(String name)
{
trueIdentity = name;
}
public String getName()
{
return trueIdentity;
}
public String sayTrueIdentity()
{
return "Hello, I'm " + trueIdentity + "!";
}
// write any format you want to print
#override
public String toString()
{
return this.getName() + this.sayTrueIdentity();
}
}
then change your GenericMethod_violette.print method to use toString()
public static <E> void print(E[] list) {
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
Reason for Avengers print format - Avengers#15db9742
In java all objects have a toString() method, which is invoked when you try and print the object.
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an # symbol and the hashcode of the object in hexadecimal. The code for this looks like:
// Code of Object.toString()
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So you need #overrride toString method.
Your print result of Avengers#15db9742 would mean that it is an object that you printed. If you want to print something meaningful, you need to override the toString() method of said object. In this case, of your Avengers object.
public String toString(){
return trueIdentity;
}
Added notes from #markspace of java toString().
The class Avengers doesn't override the Object::toString method which System.out.println implicitely uses in its implementation. I suggest you to read more at: How to override toString() properly in Java?.
However, this solution requires all the possible objects passed into the method to override such method, which you cannot guarantee. I recommend you to pass a Function<E, String> that exctracts from the generic type the field(s) as String to be printed out:
public static <E> void print(E[] array, Function<E, String> extractor) {
for (E e: array) {
System.out.print(extractor.apply(e) + " ");
}
System.out.println();
}
The usage is fairly simple (the generic type can be omitted as long as it is inferred):
// both following lines are basically identical
GenericMethod_violette.print(avenger, a -> a.getName());
GenericMethod_violette.print(avenger, Avenger::getName);
// if Avengers have more of the fields or they are to be customized, ex.:
GenericMethod_violette.print(avenger, a -> "Mr." + a.getName().toUpperCase());
Disclaimer: This solution requires Java 8. If you use Java 7 or lower, you are stick to override the Object::toString in all the expected classes:
#Override
public String toString() {
return this.getName();
}

Why does System.out.println applied to this object print this phrase? [duplicate]

This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 3 years ago.
I've got two classes, below. When I run the class TestSimple, it prints out "blueblueblue is blue repeated". That print statement is executed as System.out.println(item) which is an instance of the Simple() class. I've never seen an object print out as a phrase before, and I'm having a hard time pinning down why this is happening.
I see that there is a method in the Simple class called toString which should print this out when it is called, but I don't see that method called anywhere. What's going on here?
public class Simple {
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
And
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
public static void main(String[] args) {
new TestSimple().print();
}
}
System.out is a PrintStream, PrintStream.println(Object) (from the linked Javadoc) calls at first String.valueOf(x) to get the printed object's string value and String.valueOf(Object) returns the value of obj.toString()

My arraylist is displaying object address not object contents [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
arraylist displays object address not actual object , program usesinheritance where salesEmployee is the super class and salesAgent and salesPerson are the subclasses.
import java.util.Scanner;
import java.util.ArrayList;
public class tester {
public static void main(String[]args ) {
ArrayList <salesEmployee> listemps= new ArrayList <salesEmployee>();
Scanner user_input= new Scanner(System.in);
salesPerson emp1 = new salesPerson();
emp1.setName("Frank Long");
emp1.setppsNumber(65783);
System.out.println("Enter total value of sales earned by Frank Long");
double valeSale;
valeSale=user_input.nextDouble();
emp1.setvalSale(valeSale);
emp1.getCommission();
listemps.add(emp1);
for ( int j=0; j<listemps.size(); j++ )
System.out.println("element " + j + ": " + listemps.get(j) );
}
}
This is my salesPerson class
public class salesPerson extends salesEmployee{
public salesPerson() {
}
public salesPerson(String name, int ppsNumber, double valSale, double commission) {
super(name, ppsNumber,valSale,commission);
}
public void getCommission() {
commission=valSale*0.15;
}
public String toString2() {
return toString1()+"value of sales"+getvalSale()+"commission:"+commission;
}
}
I'll make it more elegant later for now I am just trying to get it to work
Updated: Based on the comments to my answer, there is a different issue at play. Here's what was added in the comments:
Enter total value of sales earned by Frank Long 22.00
Exception in thread "main" java.lang.StackOverflowError at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) – lucylio 5 mins ago
Is what comes up – lucylio 5 mins
In order for something reasonable to be displayed, you need to implement toString method in your class. You do have toString1 and toString2, but seemingly, no toString. (You haven't posted the code for salesEmployee class - but most likely it also doesn't have toString implementation).
In absence of toString, default Object.toString is called, which displays the address of the object.
Implement toString - and you'll see your results.
UPDATE: As the error you indicated doesn't correspond to the code, I'll go on a whim and suggest that, probably your toString2 method is actually toString and your toString1 method is actually a toString defined in your parent class, i.e. salesEmployee.java. In this case, instead of calling toString() from inside your toString method, use super.toString() instead:
public class salesPerson extends salesEmployee {
...
public String toString2() {
return super.toString()+"value of sales"+getvalSale()+"commission:"+commission;
}
}

Array prints memory address despite Override [duplicate]

This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?
The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}
Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list

java print string gives pointer number

I'm working on a special pathfinding system in java, which needs to print it's path at one point. It's far from done but I ran into a problem. When I run my code it instead prints a pointer towards an string rather then the string itself. Here is the code:
public class node {
int optionnum;
node[] options;
String[] dirrections;
String[] route;
boolean[] visited;
public node(){
options= new node[4];
dirrections= new String[4];
route= new String[50];
for (int i=0;i<50;i++){
route[i]="";
}
visited= new boolean[50];
}
public void revmdp(int num){
visited[num]=true;
for(int i=0;i<optionnum;i++){
System.out.println(options[i].route[0]); //how can this be a pointer?
options[i].revmdp(dirrections[i],num);
}
public void revmdp(String nroute, int num){
//System.out.println(route[0]+dirrections[0]);
if (!visited[num]||nroute.length()<route[num].length()){
route[num]=nroute;
visited[num]=true;
for(int i=0;i<optionnum;i++){
options[i].revmdp(route+dirrections[i],num);
}
}
}
}
output looks like this
[Ljava.lang.String;#2d66a22b3;
As you can see in the constructor of path I already set the path towards the string "" (empty string). As the string is not yet changed any futher at moment this code is called I would expect it to return "" however it instead gives these weird string pointers. Anybody know what's up?
Note I have already tried to call route[0][0] but java won't allow that.
Update 3: I found it.
options[i].revmdp(route+dirrections[i],num);
Here you are doing string concatenation on an array and a String. This causes to set route[num] in the level of recursion to this concat result.
Each Java class inerhits from the class Object, which implements the default toString() method. The Source code of the default toString() Method looks like :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
If you do not override the default toString() method, the method above is called.

Categories