简体   繁体   中英

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. 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.

    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:

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.

int maxSpeed = 200;
double gasLiter = 60;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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