简体   繁体   中英

Creating arrays using Joptionpane input

Create a program that will count the number of times an input name appeared in a list from an input array of 10 names. Using JOptionPne.

(After input of 10 names and for a name to count from the list, and assuming Maria is the name entered to count)

Expected sample output

My code so far:

import javax.swing.JOptionPane; 

public class Chapter4Act_Array { 

    public static void main(String[] args) { 
        String ArrayOf_Names[] = new String[10]; 
        for (int i = 0; i < ArrayOf_Names.length; i++) { 
            ArrayOf_Names[i] = JOptionPane.showInputDialog("Enter name" + (i + 1) + ":"); 
        } 
        System.out.println("Your friends are: "); 
        for (int i = 0; i < ArrayOf_Names.length; i++) {
            System.out.println(ArrayOf_Names[i]); 
        }
    }
}

Little short on information but I think i know what you are trying to accomplish. In the demo code below, a JOptionPane is used to acquire the names from a User. Do do this a custom panel is created and passed to the JOptionPane#showOptionPane() method:

在此处输入图像描述

Yes...that's a JOptionPane. This is most likely more than you require but then again there isn't enough info to clarify either way. In any case, here is the code and be sure to read all the comments in code (comments always make the code look more than it really is):

/* Create a JPanel object to display within the JOptionPane
   and fill it with the components we want.          */
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
    
JLabel msg = new JLabel("<html><center><font size='4'>Please enter <font "
                      + "color=blue>User</font> names into the list below:"
                      + "</font></html>");
msg.setVerticalAlignment(JLabel.TOP);
msg.setPreferredSize(new Dimension(135, 60));
jp.add(msg, BorderLayout.NORTH);
   
// Add a JTextfield and JLabel
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
JLabel name = new JLabel("Enter Name:");
JTextField textField = new JTextField(0);
textPanel.add(name, BorderLayout.NORTH);
textPanel.add(textField, BorderLayout.SOUTH);
jp.add(textPanel, BorderLayout.CENTER);
    
// Add a JList (in a JScrollPane) and Add/Remove buttons
JPanel listPanel = new JPanel();
DefaultListModel<String> listModel = new DefaultListModel<>();
JList<String> list = new JList<>(listModel);
    
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(120, 150));
scrollPane.setViewportView(list);
listPanel.add(scrollPane, BorderLayout.WEST);
    
// Add/Remove Buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
    int listItemCount = 0;
    @Override
    public void actionPerformed(ActionEvent e) {
        if (textField.getText() != null) {
            listModel.addElement(textField.getText());
            if (listModel.getSize() == 10) {
                addButton.setEnabled(false);
                return;
            }
        }
        textField.requestFocus();
        textField.setSelectionStart(0);
        textField.setSelectionEnd(textField.getText().length());
    }
});
buttonPanel.add(addButton, BorderLayout.NORTH);
    
JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
    int listItemCount = 0;
    @Override
    public void actionPerformed(ActionEvent e) {
        int selectedIndex = list.getSelectedIndex();
        if (list.getSelectedIndex() >= 0) {
            listModel.remove(selectedIndex);
        }
        if (listModel.getSize() < 10) {
            addButton.setEnabled(true);
        }
        if (selectedIndex > 0) {
            list.setSelectedIndex(selectedIndex - 1);
        }
    }
});
buttonPanel.add(removeButton, BorderLayout.CENTER);
    
listPanel.add(buttonPanel, BorderLayout.EAST);
jp.add(listPanel, BorderLayout.SOUTH);
    
// Supply what we want the dialog button captions are to be.
Object[] buttons = {"Process", "Cancel"};
    
// Display the JOptionPane using the Option Dialog.
int res = JOptionPane.showOptionDialog(this, jp, "User Names", 0, 
                      JOptionPane.PLAIN_MESSAGE, null, buttons, 1);
   
// The following code will no run until the JOptionPane is closed. 
/* If the list does not contain 10 names then inform 
   the User and make him/her do it over again.    */
if (listModel.getSize() < 10) {
    System.out.println("Not Enough Names! Do it again!");
    return;
}
    
/* Fill a String[] Array with the names in List but,
   at the same time keep track of how many times a
   specific name was in that list. We use a Map/HashMap
   to hold the occurrences information. You really don't
   need a String[] Array since the Map can take care of 
   everything but I thought you might want them separate. */
String[] names = new String[listModel.size()];   // Declare a String[] Array
Map<String, Integer> nameMap = new HashMap<>();  // Declare a Map
    
// Iterate through the List that was in the dialog using the List Model
for (int i = 0; i < listModel.size(); i++) {
    // Get name from list at current index
    names[i] = listModel.get(i); 
    // Is the name already in the Map?
    if (nameMap.containsKey(names[i])) {
        // Yes, it is ...
        // Get the current number of times Count Value for that specific name 
        int value  =  nameMap.get(names[i]);
        value++;  // Increment that value by 1
        nameMap.put(names[i], value); // Update the count value for that specific name.
    }
    else {
        /* No, it isn't so add the Name as key and 
           a count value of 1 for the value.     */
        nameMap.put(names[i], 1);
    }
}
    
/* Processing the name information is now complete,
   we just need to diplay the acquired data now held
   within the names[] Array and the nameMap Map.  */
    
/* Display the oringinal list which is now 
   contained within the names[] String Array.  */
for (int i = 0; i < names.length; i++) {
    System.out.printf("%-12s%-15s%n", "Name #" + (i+1), names[i]);
}
    
System.out.println();
    
/* Now, display the occurrences for all those 
   names held within nameMap.             */
String n;
int o;
for (Map.Entry<String,Integer> entry : nameMap.entrySet()) {
    n = entry.getKey();
    o = entry.getValue();
    System.out.println(n + " appeared " + o 
            + (o > 1 ? " times" : " time") + " in the List.");
}
System.out.println();
System.out.println("Process Completed.");
// DONE

If you run this code, your Console Window should display something like this:

Name #1     Bill           
Name #2     Jane           
Name #3     Marie          
Name #4     Tracey         
Name #5     Fred           
Name #6     Bill           
Name #7     Marie          
Name #8     Doug           
Name #9     Marie          
Name #10    Tracey         

Marie appeared 3 times in the List.
Bill appeared 2 times in the List.
Fred appeared 1 time in the List.
Jane appeared 1 time in the List.
Doug appeared 1 time in the List.
Tracey appeared 2 times in the List.

Process Completed.

EDIT: Based on comments!

Now that you have provided more info, here is one way it can be achieved. Again, read the comments in code:

public class Chapter4Act_Array {

    public static void main(String[] args) {
        String arrayOfNames[] = new String[10];
        for (int i = 0; i < arrayOfNames.length; i++) {
            // Letter case will be ignored during the occurrences processing.
            arrayOfNames[i] = JOptionPane.showInputDialog(null, "Please Enter name #" + (i + 1) + ":", "Name",JOptionPane.QUESTION_MESSAGE);
        }

        System.out.println("Your friends are: ");
        for (int i = 0; i < arrayOfNames.length; i++) {
            System.out.println(arrayOfNames[i]);
        }
        System.out.println();

        /* List to keep track of the names we've already processed.
           This will help to prevent printing the same Name more
           than once.        */
        java.util.List<String> namesAlreadyProcessed = new java.util.ArrayList<>();
        
        int counter;
        for (int i = 0; i < arrayOfNames.length; i++) {
            counter = 1;
            for (int j = 0; j < arrayOfNames.length; j++) {
                if (j == i) { continue; } // If we fall onto the same index then skip past it.
                if (arrayOfNames[i].equalsIgnoreCase(arrayOfNames[j])) {
                    counter++;
                }
            }
            
            /* If counter is greater than 1 then there has been 
               a name we've encountered more than once. Let's 
               display the number of times it was encountered
               and add that name to namesAlreadyProcessed List. */
            if (counter > 1) {
                // Have we already processed this name?
                boolean processed = false;
                for (String name : namesAlreadyProcessed) {
                    if (name.equalsIgnoreCase(arrayOfNames[i])) {
                        // Yes, so skip printing the result again for this name.
                        processed = true;
                        break;
                    }
                }
                /* If No, then let's print the name and count result to 
                   Console Window and add the name to our List.     */
                if (!processed) {
                    System.out.println(arrayOfNames[i] + " is in the List " + counter + " times.");
                    namesAlreadyProcessed.add(arrayOfNames[i]);
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM