java - 如果语句不更新同一类中的私有字段
问题描述
所以我有这个类的代码:
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");
}
这就是我在主类中使用它的方式:
car.velocityManagement(10);
car.velocityManagement(15);
car.velocityManagement(-20);
预期输出:
- 踩油门
- 速度增加到 10 公里/小时
- 踩油门
- 速度增加到 25 公里/小时
- 按下休息
- 速度降至 5 公里/小时
实际输出:
- 踩油门
- 速度增加到 10 公里/小时
- 踩油门
- 速度增加到 25 公里/小时
- 按下休息
- 速度降至 45 公里/小时
解决方案
当速度为负时,您减去一个负数,这与添加一个正数相同:
// When speed is negative, this corresponds to adding
// the absolute value of speed to velocity
velocity -= speed;
您应该添加此负数。只有打印语句应该在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;
}
最好的
推荐阅读
- matlab - 关闭图形窗口会导致打开一个新的图形窗口
- python - 使用 openpyxl 模块将值复制到 Excel 工作表
- android - 如果设备在开发人员菜单中没有此选项(华为),是否可以在 Android(Xamarin.Forms)上禁用 WiFi 节流?
- javascript - 具有 setTimeout 功能的点击事件。点击目标丢失
- google-sheets - INDIRECT 参数值在另一个选项卡中无效
- flutter - Flutter TextField:如何在右侧添加图标
- axapta - 如何从 ax2012 的自定义查找中获取选定的查找值
- flutter - ActionBar 中的 Fluttter 搜索栏,如 yelp 应用
- azure-synapse - 用于 Synapse 专用池的 OPENROWSET()?
- python - 不支持的索引分配目标