How to print a specific instance of an object using toString

348 Views Asked by At

How would I print and specific instance of an object using a toString?

So basically the user is inputing information. based on the input it will either saved in instance A or Instance B. Both instance A and B are subclasses with overriding toString methods. so the input from the user is saved in an array. How can I make it so that all the inputs that was an instance of A will print?

This is the code I currently have and it is not working.

public static void printA(ABC[] inputs)
    {
        for(int i = 0; i < inputs.length; i++)
        {   
            if(inputs[i] instanceof A)
            {
                JOptionPane.showMessageDialog(null, inputs.toString());
            }
        }
    }
2

There are 2 best solutions below

2
On BEST ANSWER

you just need is

JOptionPane.showMessageDialog(null, inputs[i].toString());

cuz you are trying to show the array.toString() not the value you want to.

5
On

You are iterating inputs, but testing clients. This is why I prefer to use a for-each loop and I suggest you use a StringBuilder to build a single 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 output you're getting ("LClient;@20d9896e") is because you are displaying inputs.toString(). Array doesn't override toString(), you can use Arrays.toString(Object[]) like

String msg = Arrays.toString(inputs);

But you'll get all of the items in the array. Also, make sure Client overrides toString().