-4

I'm trying to print every item in my array, but it gives me a value like PackOfCrisps@653f6b99. I have tried inputting toString() but that just tells me it cannot be converted to a string.

(PackOfCrisps is a separate class)

I'm really new to this

eeee
  • 1
  • 1
  • What do you expect to be outputted...? You're trying to print a class instance so instead it gives you the address it lives at in memory. – kelsny Nov 05 '22 at 18:20
  • 1
    *I have tried inputting toString()* Please show what you did – g00se Nov 05 '22 at 18:21
  • I'm trying to get it to print the items that are added into the array by the user, and with toString I changed the System.out.println to System.out.println(packOfCrisps(Arrays.toString(pCK))); – eeee Nov 05 '22 at 18:23
  • I don't see the code I asked for..? – g00se Nov 05 '22 at 18:26
  • Sorry I don't understand - I've added an example to the bottom of the code if that helps? – eeee Nov 05 '22 at 18:29
  • 2
    You need to implement a toString() method in PackOfCrips, returning the information from PackOfCrips you want to display. – Christoph Dahlen Nov 05 '22 at 18:43
  • Hello OP. Your question seems valid but you need to provide the sample code (the Java class) that you tried to run and faced errors in. I see that there is a possible answer below for this question now. But adding the code will help others understand your question and help you get better answers. – Anu Shibin Joseph Raj Nov 09 '22 at 11:49

1 Answers1

0

"PackOfCrisps@653f6b99" is the result of the default Object.toString() function. You need to Override the method in your PackOfCrisps class to actually return something useful.

class PackOfCrisps {
    ...
    @Override
    public String toString() {
        return String.format("PackOfCrisps (flavor: %s)", flavor); 
    }
}

In toString() you can return whatever you want, and also include whatever attributes your class has (like flavour for example).

Javadocs for Object.toString() in case you're interested: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()

yanjulang
  • 57
  • 4
  • 1
    this makes sense to me, but now I recieve 'toString() in PackOfCrisps cannot override toString() in java.lang.Object' and 'return type void is not compatible with java.lang.String' – eeee Nov 05 '22 at 18:54
  • woops, mistake on my side. toString() of course returns a String, I've updated the answer – yanjulang Nov 05 '22 at 19:01