How can I display the whole array in one message dialog box from multiple inputs? The code is supposed to ask user how many numbers they want entered, have the user enter those numbers, then display them in reverse order. Everything seems to be working except that the output displays a separate message box for each number in the array and I want them all in one with spaces or commas in between. Advice?
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog
(null, "How many numbers do you want to enter?");
int count = Integer.parseInt(input);
double[] myList = new double[count];
for(int a = 0; a < count; a++)
{
String numberInput = JOptionPane.showInputDialog
(null, "Enter a number: ");
int number = Integer.parseInt(numberInput);
myList[a] = number;
}
double[] secondList = reverse(myList);
printArray(secondList);
}
public static double[] reverse(double[] list)
{
double[] result = new double[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--)
{
result[j] = list[i];
}
return result;
}
public static void printArray(double[] array)
{
for (int a = 0; a < array.length; a++)
{
JOptionPane.showMessageDialog(null, array[a] + " ");
}
}
JOptionPane.showMessageDialog(null, array[a] + " ");
is in a loop, so it will. You should instead construct the output message in your for loop and call JOptionPane.showMessageDialog
once with the message you want to show.
public static void printArray(double[] array) {
StringBuilder builder = new StringBuilder();
for (int a = 0; a < array.length; a++) {
builder.append(array[a]).append(" ");
}
JOptionPane.showMessageDialog(null, builder.toString());
}
Something like that should work. It's been a while since I've done Java so apologies if it's a little off.