Hi guys!
Can anyone provide an accurate code for me to do this please.
I'm not having any luck finding particular codes on Google that work.

Dani AI

Generated

As noted, a simple for loop will do the job—but a few extra checks make the result robust and user-friendly. Below are two compact patterns: one when you know how many values to collect, and one for an unknown count. and pointed to the Swing dialog docs; the examples here show practical handling (Cancel, empty input, and basic validation) you can drop into a helper method.

// fixed-size: ask for count, then collect that many non-empty strings
public static String[] collectFixedNumber() {
    String countStr = JOptionPane.showInputDialog(null, "How many values?");
    if (countStr == null) return new String[0]; // user cancelled
    int count;
    try {
        count = Integer.parseInt(countStr.trim());
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Enter a whole number.");
        return new String[0];
    }
    String[] values = new String[count];
    for (int i = 0; i < count; i++) {
        String input = JOptionPane.showInputDialog(null, "Enter value " + (i + 1));
        if (input == null) break; // user cancelled during collection
        input = input.trim();
        if (input.isEmpty()) { i--; continue; } // re-ask same index
        values[i] = input;
    }
    return values;
}
// dynamic-size: collect until user cancels or enters a blank line
public static String[] collectUnknownNumber() {
    List<String> list = new ArrayList<>();
    while (true) {
        String input = JOptionPane.showInputDialog(null, "Enter next value (blank or Cancel to finish)");
        if (input == null) break;
        input = input.trim();
        if (input.isEmpty()) break;
        list.add(input);
    }
    return list.toArray(new String[0]);
}

Troubleshooting notes: always check for null (Cancel/close) and for empty strings; when expecting numbers wrap parsing in try/catch for NumberFormatException and re-prompt on error; prefer an ArrayList when the count is unknown; and run UI code on the Event Dispatch Thread (SwingUtilities.invokeLater) to avoid threading issues. These small checks prevent common bugs (nulls, off-by-one, uncaught parse errors) and make the dialog flow much more reliable.

Recommended Answers

All 3 Replies

I tried the Oracle site, didn't help me much...cause it just basically gives different examples of input boxes but I eventually figured it out.
Just used a for loop to store the input in a array.

but thanks guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.