具有两个参数但不需要同时使用两个参数的 Void 函数

Void function with two arguments but not both need to be used

第一个技术挑战赛,机器人组织现在有一个 android 平台而不是乐高。我的团队正在过渡到 java,但我有一个简单的问题。如果我有一个函数有两个参数 power1power2 并且都可以设置为双精度但如果没有指定第二个参数,它应该 运行 两个电机只有power1 变量。这是我的代码:

package com.qualcomm.ftcrobotcontroller.opmodes;

public class BasicFunctions extends HardwareAccess {

    /*
    This file lists some basic funcions on the robot that we can use without typing large amounts of code.
    To use this code in the opmode add "extends BasicFunctions" to the end of the class line
     */
    public void setDriveMotorPower(double power1, double power2) {
        if (power2 = null) {
            motorLeft.setPower(power1);
            motorRight.setPower(power1);
        }

        motorLeft.setPower(power1);
        motorRight.setPower(power2);

    }

    public void init() {

    }

    @Override
    public void loop() {

    }
}

更新: 这是 Android Studio 的截图:

如果一个函数有 2 个参数,您必须同时发送它们,但还有另一个想法:如果您不想使用 power2,例如您可以传递一些不可能发生的值喜欢 -1 或任何根据您的情况然后检查 if(power2 == -1) 这比检查 null 更好。
顺便说一下,方法 .setPower() for 将被调用 4 次,因为你刚刚使用了 if 而不是 if else。应该是

motorLeft.setPower(power1);
if (power2 == null) { // or -1 like I said before
        motorRight.setPower(power1);
} else {
    motorRight.setPower(power2);
}

这里有几个问题:

  1. 原始 double 不能是 null,您必须使用 java.lang.Double 包装器。
  2. = 是赋值运算符。使用 == 运算符来测试相等性。
  3. 无论是否执行,您都在 if 之后使用 power1power2。相反,您可能打算使用 else 子句:


public void setDriveMotorPower(Double power1, Double power2) {
    motorLeft.setPower(power1);
    if (power2 == null) {
        motorRight.setPower(power1);
    } else {
        motorRight.setPower(power2);
    }
}