How to use JOptionPane to input data into an array

2019-09-01 03:50发布

问题:

how do i create an array where I want there to be 8 values in an array but the user inputs them?

this is what i have so far

                    import javax.swing.JOptionPane;

                    public class Southside Report {
                       public static void main(String[] args) {

                       int FINAL MIN_STAFF = 7;
                       int total_staff = 0;

                       double[] num_students = 8; 

回答1:

you should declare your array as:

double[] num_students = new double[8];

And int FINAL MIN_STAFF = 7; should be FINAL int MIN_STAFF = 7;

Then you may assign the value using JOptionPane by doing:

int i=0;
while(i<8){
   try{
       num_students[i]=Double.parseDouble(JOptionPane.showInputDialog("Enter Number:"));
       i++;
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, "Please enter valid number");
    }
}


回答2:

Take a look to JOptionPane. Option Panes are very customizable. Besides that your code not compile i think that you want the user to input 8 text only in one dialog and you can do it with optionPane with little customization like below example.

import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class JOptionPaneTest {

    public static final int OPTIONS = 8;
    private List<JTextField> textfields = new ArrayList<>(OPTIONS);

    private JPanel panel;


    public JOptionPaneTest(){
        panel = new JPanel();

        for(int i =0;i< OPTIONS;i++){
            JTextField textfield = new JTextField(5);
            textfields.add(textfield);
            panel.add(new JLabel(Integer.toString(i+1)+": "));
            panel.add(textfield);
        }

    }


    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
          JOptionPaneTest example = new JOptionPaneTest();
          int result = JOptionPane.showConfirmDialog(null, example.panel, 
                   "Please Enter Values", JOptionPane.OK_CANCEL_OPTION);
          if (result == JOptionPane.OK_OPTION) {
             for(JTextField textfield : example.textfields){
                 System.out.println(textfield.getText()); 
             }

          }
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

And output: