简体   繁体   中英

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();

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.

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