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){

Upvotes: 1

Views: 287

Answers (4)

Manmeet Anand
Manmeet Anand

Reputation: 1

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;
}

Upvotes: 0

corroborator
corroborator

Reputation: 321

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

Upvotes: 1

Beri
Beri

Reputation: 11610

@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   
}

Upvotes: 0

Eran
Eran

Reputation: 393791

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.

Upvotes: 1

Related Questions