tkay87
tkay87

Reputation: 13

How to stop user input in array when using JOptionPane

I am new in Java. I'm taking my first java class. I am trying to create a fixed size array ( for example: the array with a size is 10) and I use JOptionPane to let the user input data. My question is how can I let the user stop their input whenever they want. (For example: They just input 3 data instead of 10 and they want to finish it). This is my first post, I'm sorry if the format is not correct. Thank you guys.

import java.util.Arrays;
import javax.swing.JOptionPane;
public class TestArray {

/**
 * @param args
 */
public static void main(String[] args) {
    String[] lastName = new String[10];
    for (int i = 0; i < lastName.length; i++)
    {
        lastName[i] = JOptionPane.showInputDialog(null,"Please Enter  Tutor Last Names: " );

    }
    JOptionPane.showMessageDialog(null, lastName);

Upvotes: 1

Views: 2999

Answers (2)

Reimeus
Reimeus

Reputation: 159844

Just break out of the loop when you encounter a null value or empty String. Click cancel or enter an empty String to break from the loop.

for (int i = 0; i < lastName.length; i++) {
    lastName[i] = 
          JOptionPane.showInputDialog(null, "Please Enter  Tutor Last Names:");
    if (lastName[i] == null || lastName[i].isEmpty()) {
        break;
    }
}

Upvotes: 1

karan
karan

Reputation: 8853

just put a check using certain variable and prompt user at end of every cycle to continue or not...if user wants to quit simply use break;

but it is good practice that to get the no of iteration prior to rotating loop...ask user that for how much no of time they want to execute the steps...store it in variable and use that as exit condition...

Upvotes: 0

Related Questions