Search code examples
javajoptionpane

Sorting names and using JOptionPane to show output


So my code so far is this...

      import javax.swing.*;
        public class TestNo2{
          public static void main(String[] args){
            String[] nameNum = new String[0];
            int numberNames;
            JTextField inputName = new JTextField(5);
              JPanel nameWindow = new JPanel();
                nameWindow.add(new JLabel("How many names would you like to sort?"));
                nameWindow.add(inputName);

            int numNames = JOptionPane.showConfirmDialog(null, nameWindow
                ,"Accept and sort list of students."
                ,JOptionPane.OK_CANCEL_OPTION);
            if(numNames == JOptionPane.OK_OPTION){

              String numNamesS = inputName.getText();
              numberNames = Integer.parseInt(numNamesS);
              nameNum = new String[numberNames];


              for(int counterOne=0;counterOne<nameNum.length;counterOne++){
                for(int counterTwo=1;counterTwo<=nameNum.length;counterTwo++){
                  nameNum[numberNames] = JOptionPane.showInputDialog(null
                    ,"Enter the name of student "+counterTwo
                    ,"Name Input"
                    ,JOptionPane.QUESTION_MESSAGE);
                }   
              }      
            }           
          } 
        }

There's no error when I build it but when I run the program, I would only be allowed to enter one name then the error occurs.

This is the error that shows up.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at TestNo2.main(TestNo2.java:23)

Thank you for your time in reading this.


Solution

  • for(int counterTwo=1;counterTwo<=nameNum.length;counterTwo++){
    

    should be:

    for(int counterTwo=1;counterTwo < nameNum.length;counterTwo++){
    

    Because the expression counterTwo<=nameNum.length causes the array to exceed its bounds (remember that actual length of array starts from zero and is 1 Less than actual length you specified.

    So if you have an array defined like:

    someArray[] something = {1,2,3,4,5,6};
    

    The value of something.length would be 6. But the actual length is 5 (Counting as: 0,1,2,3,4,5).

    And why do you have two loops for just gettings names and adding to String Array? Just one is enough...

    for(int counterOne=0;counterOne<nameNum.length;counterOne++){
        nameNum[counterOne] = JOptionPane.showInputDialog(null
                            ,"Enter the name of student "+(counterOne+1)
                            ,"Name Input"
                            ,JOptionPane.QUESTION_MESSAGE);
    }
    

    And then sort the array nameNum with whatever method you plan to use.