Kevin Schultz
Kevin Schultz

Reputation: 884

Error checking if statements

I am doing some practice work by expanding on a homework project I recently wrote. This is not for a grade, but I want to add some error checking to my code.

The program requires you to enter a name, select from a dropdown, select from a listbox and to select a radio button. My goal is to populate an error messagebox if any of the required items is blank.

The code I have so far for the error checking is below, but Im not sure how to take the individual lacking item and populate that to the message box since all of the error checking is in a single "if" statement.

Error checking code:

// Listener to handle the print button.
class ButtonListener implements ActionListener
{
    ButtonListener() {}

    public void actionPerformed(ActionEvent e)
    {
        JFrame frame1 = new JFrame("Show Message Dialog");

        // Checks for required entries
        if (error == 0 || name == "" || flag == 0)
        {
            JOptionPane.showMessageDialog(frame1,
                    "You must complete the form: " +     missing, "ERROR",
                JOptionPane.ERROR_MESSAGE);
        }
        else
        {
            // Get values from fields
            setText();
            System.out.println("Passenger's Name: " + name + "\n");
            System.out.println("Age Group: " + ageValue + "\n");
            for (int i = 0; i < value.length; i++)
            {
                System.out.println("Destination: " + value[i]   + "\n");
            }
            System.out.println("Departure Day: " + day  + "\n");
        }
    }
}

Thanks!

Upvotes: 3

Views: 2498

Answers (1)

Jeremy Pridemore
Jeremy Pridemore

Reputation: 1995

It looks like they can actually have multiple things wrong, so why only show one? I'm normally a C# dev so I'm not going to try to get the syntax right on typing this myself, but here's the concept:

  • Create a collection of some sort, like a list of strings.
  • Make 3 if statements, one for each of those errors, and put the field names in for each one that fails. if (name.isEmpty()) { errorList.Add("name"); }
  • Check to see if the count of items in the list is greater than 0. If it is throw your error and put the name of the bad fields from the collection into the string that you generate.

Upvotes: 4

Related Questions