gpt4 book ai didi

java - 我可以使用逻辑或运算符来测试 if 语句中的两个条件吗?

转载 作者:行者123 更新时间:2023-12-01 08:06:41 26 4
gpt4 key购买 nike

我有一个开始按钮和一个弹出菜单选项,可以做同样的事情。是否可以在同一个 if 语句中测试两个按钮,或者我是否必须为它们编写两个单独的 if 语句?

我想做这样的事情:

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

最佳答案

这里唯一的问题是括号。 if 语句的形式如下:

if (condition)
body

目前你已经

if (condition1) || (condition2)
body

这是无效的。你只是想要:

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

或者可能提取出共性:

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

如果您确实需要,可以添加额外括号:

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

...但括号中必须只有一个整体表达式。

关于java - 我可以使用逻辑或运算符来测试 if 语句中的两个条件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20985732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com