How to remove a team name (String) from an Array read from a data file?

42 Views Asked by At

I am trying to make an input dialog that prompts the user to select a second team that plays the first team. The team the user selected before cannot show again and there needs to be an error check if the user inputs something that isn't a team option. I am using a class called Team to get the team names from a data file. I have already created the method to select the first team. This is the desired output: The message for the user to select two teams

I made a while loop that keeps running if the user inputs the first team again or something that wasn't a team option. I made a different JOptionPane Input Dialog for each team and thought that the user could input anything and the code would check if its valid. **However, when the program runs, it skips the method entirely. ** *League * is the array of teams with wins and losses and their roster (players). This method has two formal parameters that accepts the league array and the user's first team selection called team1. This method is supposed to return the second team selection.
This is my code currently:

for (int i = 0; i < league.length; i++) {
            while (!team2.equalsIgnoreCase(league[i].getName()) && team2.equals(team1)) {
                if (team1.equals(league[0].getName())) {
                    display = JOptionPane.showInputDialog("Select a team to play the " + team1 + "\n\n"
                            + "-" + league[1].getName() + "\n"
                            + "-" + league[2].getName() + "\n"
                            + "-" + league[3].getName() + "\n\n");
                } else if (team1.equals(league[1].getName())) {
                    display = JOptionPane.showInputDialog("Select a team to play the " + team1 + "\n\n"
                            + "-" + league[0].getName() + "\n"
                            + "-" + league[2].getName() + "\n"
                            + "-" + league[3].getName() + "\n\n");
                } else if (team1.equals(league[2].getName())) {
                    display = JOptionPane.showInputDialog("Select a team to play the " + team1 + "\n\n"
                            + "-" + league[0].getName() + "\n"
                            + "-" + league[1].getName() + "\n"
                            + "-" + league[3].getName() + "\n\n");
                } else if (team1.equals(league[3].getName())) {
                    display = JOptionPane.showInputDialog("Select a team to play the " + team1 + "\n\n"
                            + "-" + league[0].getName() + "\n"
                            + "-" + league[1].getName() + "\n"
                            + "-" + league[2].getName() + "\n\n");
                } else {
                    popup("Sorry, I couldn't find " + team2 + ", please try again...");
                }
            }
        }

Any help would be great!

1

There are 1 best solutions below

0
DevilsHnd - 退した On

You may instead want to try something a little different. Perhaps use a couple of JComboBoxes to hold team names. When team name is selected from the first Combobox then drop that name from the second Combobox. The second ComboBox won't even become active until the first Combo has a selected name. The OK button won't become enabled until the second ComboBox has a selected name. This is demonstrated within the below GIF:

enter image description here

Here is the runnable code. Be sure to read all the comments in code:

public class PlayTeamsDemo {

    // Class Member Variables:
    /* List of Team Names to be used in JComboBoxes. List<String> is
       used due to its flexability:        */
    private java.util.List<String> teamNames = java.util.Arrays.asList(
            "Toronto Raptors", "Chicago Cows", "Orlando Tricks", "Boston Gaelics"
            );
    
    String team1 = "";  // Will hold the first selected team (default null string).
    String team2 = "";  // Will hold the second selected team (default null string).
    
    // Swing component that requires class global access:
    javax.swing.JDialog dialog;
    javax.swing.JLabel topTitle;
    javax.swing.JComboBox teamNamesCombo;
    javax.swing.JLabel bottomTitle;
    javax.swing.JComboBox otherTeamNamesCombo;
    javax.swing.JButton okButton;
    javax.swing.JButton cancelButton;
    
    // Constructor:
    public PlayTeamsDemo() {
        initForm();  // Create the dialog and display:
    }

    private void initForm() {
        // Dialog Frame...
        dialog = new javax.swing.JDialog();
        dialog.setTitle("Team Play:");
        dialog.setResizable(false);
        dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        dialog.setSize(300, 210);
        dialog.setAlwaysOnTop(true);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(null);

        // Dialog Main JPanel...
        javax.swing.JPanel mainPanel = new javax.swing.JPanel();

        // Upper Panel...To hold Top Title JLabel and first JComboBox:
        javax.swing.JPanel firstTeamPanel = new javax.swing.JPanel(new java.awt.GridLayout(2, 1));
        topTitle = new javax.swing.JLabel("Select a team:");
        firstTeamPanel.add(topTitle);

        teamNamesCombo = new javax.swing.JComboBox();
        teamNamesCombo.setModel(new javax.swing.DefaultComboBoxModel<String>(
                teamNames.toArray(new String[0])));
        teamNamesCombo.setPreferredSize(new java.awt.Dimension(200, 25));
        teamNamesCombo.setSelectedIndex(-1);
        
        // Top Combo ItemListener
        teamNamesCombo.addItemListener(new java.awt.event.ItemListener() {
            @Override
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                // If a team name was actually selected:
                if (!teamNamesCombo.getSelectedItem().toString().isEmpty()) {
                    // Load the second JComboBox with Team Names...
                    otherTeamNamesCombo.setModel(new javax.swing.DefaultComboBoxModel<String>(
                                                 teamNames.toArray(new String[0])));
                    // Make sure nothing is selected in second JComboBox:
                    otherTeamNamesCombo.setSelectedIndex(-1);
                    // Apply the selected team name from fist combobox to team1 variable:
                    team1 = teamNamesCombo.getSelectedItem().toString();
                    // Get the selected index value from first ComboBox
                    int selectedIndex = teamNamesCombo.getSelectedIndex();
                    /* Remove the selected team name in first combo from
                       the second combobox so the same name can't be selected: */
                    otherTeamNamesCombo.removeItemAt(selectedIndex);
                    // Enable bottom combobox title JLabel:
                    bottomTitle.setEnabled(true);
                    // Enable the second team name combobox:
                    otherTeamNamesCombo.setEnabled(true);
                }
            }
        });
        firstTeamPanel.add(teamNamesCombo);

        // Lower Panel...To hold Bottom Title JLabel and second JComboBox:
        javax.swing.JPanel secondTeamPanel = new javax.swing.JPanel(new java.awt.GridLayout(2, 1));
        bottomTitle = new javax.swing.JLabel("Select a team to play the above: ");
        bottomTitle.setEnabled(false); // JLabel is Disabled at startup
        secondTeamPanel.add(bottomTitle);
        
        // Second team names Combobox:
        otherTeamNamesCombo = new javax.swing.JComboBox();
        otherTeamNamesCombo.setPreferredSize(new java.awt.Dimension(200, 25));
        otherTeamNamesCombo.setEnabled(false); // Combobox is Disabled at startup
        // Bottom Combo ItemListener
        otherTeamNamesCombo.addItemListener(new java.awt.event.ItemListener() {
            @Override
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                // If second combobox has an actual selected team name...
                if (otherTeamNamesCombo.getSelectedItem() != null && 
                           !otherTeamNamesCombo.getSelectedItem().toString().isEmpty()) {
                    // Apply the second team name to the team2 variable:
                    team2 = otherTeamNamesCombo.getSelectedItem().toString();
                    // Enable the OK button:
                    okButton.setEnabled(true);
                }
            }
        });
        secondTeamPanel.add(otherTeamNamesCombo);
        
        // JPanel to hold JButtons:
        javax.swing.JPanel buttonsPanel = new javax.swing.JPanel();
        // The OK Button:
        okButton = new javax.swing.JButton("OK");
        okButton.setEnabled(false);  // JButton is Disabled at startup
        // OK Button Action Listener:
        okButton.addActionListener(new java.awt.event.ActionListener() { 
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) { 
                /* If the OK button is selected then display a message box
                   indicating the teams to be in play:             */
                javax.swing.JOptionPane.showMessageDialog(dialog, team1 + " vs " + team2, 
                            "Teams in play...", javax.swing.JOptionPane.INFORMATION_MESSAGE);
                dialog.dispose();  // Dispose the dialog window:
            } 
        });
        buttonsPanel.add(okButton);
        
        // The Cancel button:
        cancelButton = new javax.swing.JButton("Cancel");
        // The Cancel button ActionListener:
        cancelButton.addActionListener(new java.awt.event.ActionListener() { 
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) { 
                // Indicate that the process has been Csnceled:
                javax.swing.JOptionPane.showMessageDialog(dialog, "Operation Canceled!", 
                            "Canceled!", javax.swing.JOptionPane.INFORMATION_MESSAGE);
                team1 = ""; // Empty the team1 variable:
                team2 = ""; // Empty the team2 variable:
                dialog.dispose();  // Dispose the dialog window:
            } 
        });
        buttonsPanel.add(cancelButton);
        
        mainPanel.add(firstTeamPanel);
        mainPanel.add(secondTeamPanel);
        mainPanel.add(buttonsPanel);
        dialog.add(mainPanel);
    }

    public static void main(String[] args) {
        // App started this way to avoid the need for statics:
        new PlayTeamsDemo().startApp(args);
    }

    private void startApp(String[] args) {
        /* Display the Dialog Window */
        java.awt.EventQueue.invokeLater(() -> {
            dialog.setVisible(true);
        });
    }
}