简体   繁体   English

如何使用循环来增加一项并减少第二项

[英]How to use for Loops to increment one item and decrement second item

i want to achieve following result: if speed increments by one gasLiter decrements by 0.25. 我想获得以下结果:如果速度增加一gasLiter,则减少0.25。 Can someone help please? 有人可以帮忙吗? this is my code what i have: 这是我的代码,我有:

public class Gas extends Car{

    public Gas (String wheels, String frame, double engine, int maxSpeed) {
        super (wheels, frame, engine, maxSpeed);

        for (int speed = 0; speed<maxSpeed; speed++) {
            for (double gasLiter= 60; gasLiter <60; gasLiter-=0.25){

You need a single loop: 您需要一个循环:

double gasLiter = 60;
for (int speed = 0; speed < 800; speed++, gasLiter-=0.25) {

}

You can also add a second stopping condition: 您还可以添加第二个停止条件:

double gasLiter = 60;
for (int speed = 0; speed < 800 && gasLiter >= 0; speed++, gasLiter-=0.25) {

}

I assumed your original gasLiter < 60 condition was a mistake. 我认为您原来的gasLiter < 60条件是错误的。

    for (int speed = 0; double gasLiter = 60; speed < maxSpeed; gasLiter>0; speed++, gasLiter-=0.25) {
            // your code 
}

@Eran had it covered, but you could also add a condition to stop, when there is no more gas left: @Eran已经覆盖了它,但是您也可以添加一个条件,以在没有更多气体可用时停止:

double gasLiter = 60;
for (int speed = 0; speed < 800 && gasLiter > 0; speed++, gasLiter-=0.25) {
   // ^ initial conditions;     ^ end conditions ; ^ increment speed, decrement gas   
}

You could add a check for gas reaching 0.0. 您可以添加一个检查气体是否达到0.0。

int maxSpeed = 200;
double gasLiter = 60;

for (int speed = 0; speed < maxSpeed; speed++) {
    gasLiter -= 0.25;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM