LooMeenin
LooMeenin

Reputation: 818

Can I use a logical OR operator to test two conditions in if statement?

I have a start button and a popup menu option that do the same thing. Is it possible to test both buttons in the same if statement or do I have to write two separate if statements for them?

I want to do something like this:

public void actionPerformed(ActionEvent e){

            // The start button and the popup start menu option
            if (e.getSource() == start)||(e.getSource() == startPopup){
                new Thread() {
                    @Override 
                    public void run() {
                        GreenhouseControls.startMeUp();
                    }
                }.start();

Upvotes: 0

Views: 219

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503489

The only problem here is the brackets. An if statement is of the form:

if (condition)
   body

Currently you've got

if (condition1) || (condition2)
   body

which isn't valid. You just want:

if (e.getSource() == start || e.getSource() == startPopup)

Or potentially extracting out the commonality:

Object source = e.getSource();
if (source == start || source == startPopup)

You can add extra parentheses if you really want:

Object source = e.getSource();
if ((source == start) || (source == startPopup))

... but there has to be just one overall expression in parentheses.

Upvotes: 6

Related Questions