How to use JOptionPane to input data into an array

前端 未结 2 1665
南旧
南旧 2021-01-28 02:20

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 ja         


        
相关标签:
2条回答
  • 2021-01-28 02:59

    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");
        }
    }
    
    0 讨论(0)
  • 2021-01-28 03:08

    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:

    enter image description here

    0 讨论(0)
提交回复
热议问题