Adr*_*ian -1 java if-statement
所以我有这个代码从类:
private int velocity = 0;
public void velocityManagement(int speed){
if (speed > 0){
System.out.println("Pressing gas pedal");
velocity += speed;
System.out.println("Velocity increased to " + velocity + " km/h");
} else{
System.out.println("Pressing break");
velocity -= speed;
System.out.println("Velocity decreased to " + velocity + " km/h");
}
Run Code Online (Sandbox Code Playgroud)
这就是我在主类中使用它的方式:
car.velocityManagement(10);
car.velocityManagement(15);
car.velocityManagement(-20);
Run Code Online (Sandbox Code Playgroud)
预期产量:
实际输出:
当速度为负数时,您要减去负数,这与添加正数相同:
// When speed is negative, this corresponds to adding
// the absolute value of speed to velocity
velocity -= speed;
Run Code Online (Sandbox Code Playgroud)
您应该添加此负数。语句上只能有打印if else语句。
public void velocityManagement(int speed){
if (speed > 0){
System.out.println("Pressing gas pedal");
System.out.println("Velocity increased to " + velocity + " km/h");
} else{
System.out.println("Pressing break");
System.out.println("Velocity decreased to " + velocity + " km/h");
}
velocity += speed;
}
Run Code Online (Sandbox Code Playgroud)
最好
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |