re: java arrays

Status
Not open for further replies.

simmadown

Seniorius Lurkius
34
I am in a beggining Java class, here is the code:

JOptionPane.showMessageDialog(null, "Here is a list of Friends:"
+ Friends.arrayNames. + "\n");

What I am trying to do is create one dialog box, containing an entire list of String names from the array. I tried a for loop,

for(int i=0;i < Friends.arrayNames.length; i++)
{
JOptionPane.showMessageDialog(null, "Here is a list of Friends:"
+ Friends.arrayNames. + "\n");
}

But this posts a new dialog box for each name in the array. Anyone have any ideas?
 

Handor

Ars Tribunus Militum
2,513
Try this:

Code:
string friendList = "Here is a list of Friends:\n";

for(int i=0;i < Friends.arrayNames.length; i++)
{
    friendList += Friends.arrayNames[i] + "\n";
}

JOptionPane.showMessageDialog(null, friendList);

Note: I haven't tested it, but this should get you on the right track.

Edit: A little more explanation...

Assuming you understand the nature of function calls and such, then you can see why it would produce the result that it did produce: The function call was inside the loop, so every time that code got executed, the message box would get displayed with whatever you passed to it. JOptionPane.showMessageDialog() (apparently) doesn't support any method of aggregating its text and then only presenting when you're through, so this means that you'll get a complete message box every time that line is hit.

So instead of manipulating the data inside the message box, you manipulate the data before you get there. You can do this by dynamically constructing your string using the data in your array. Then, at the end, you pass the whole chunk to the function, which then displays the box.
 
Status
Not open for further replies.