How to print a specific instance of an object using toString
How do I print and a specific instance of an object using toString?
So basically the user enters information. based on the input, it will either be stored in instance A or instance B. Both instances A and B are subclasses, with overriding toString methods. so the user's input is stored in an array. How can I make it so that all inputs that were instance of A are printed?
This is the code I have and it doesn't work.
public static void printA(ABC[] inputs)
{
for(int i = 0; i < inputs.length; i++)
{
if(inputs[i] instanceof A)
{
JOptionPane.showMessageDialog(null, inputs.toString());
}
}
}
source to share
You are iterating inputs
, but testing clients
. This is why I prefer to use a loop for-each
, and I suggest you use StringBuilder
to create one message and then display it once. Something like,
public static void printA(ABC[] inputs) {
StringBuilder sb = new StringBuilder();
for (ABC input : inputs) {
if (input instanceof A) {
sb.append(input).append(System.lineSeparator());
}
}
JOptionPane.showMessageDialog(null, sb.toString().trim());
}
Edit
The result you get ("LClient; @ 20d9896e") is what you display inputs.toString()
. Array does not override toString()
, you can use Arrays.toString(Object[])
for example
String msg = Arrays.toString(inputs);
But you will get all the elements in the array. Also, make sure to Client
override toString()
.
source to share