How can I create a loop that calculates the distance traveled using Java? [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I create a loop that calculates the distance traveled using Java? [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to create a loop that will contain the following instructions. A loop that calculates the distance traveled outputs the result one line at a time i.Appropriate variables must be declared and initialized. speed variable should be initialized to 75. distance variable should be initialized to zero. ii. Loop control variable should be called day. The day variable starts at 1 and goes up to 20. Here is the loop body:

1.day must be converted to hours and stored in a variable.

2.Distance traveled must be calculated. You can use the following formula: distance = time * speed.

3.distance must be incremented by 1

4.speed must be incremented by 1

5.Day, hours, speed and distance must be printed for each iteration of the loop.

I’ve tried a couple of ways but I haven’t be able to get the same result as the picture. https://i.stack.imgur.com/m1eqV.png

This my code at the moment

public static void calc(){
  System.out.println("Day tHours tSpeed t Miles");

  for (int i = 1; i <= 20; i++){
     System.out.println(i);
     }
  for (int t = 24; t <= 480; t++){
     System.out.println("tt"+ t);
     }
  }

The result is :

    Day     Hours   Speed    Miles
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

Answer

I created this code:

int speed = 75;
int distance = 0;
//initialize variables

System.out.print("DaytHourstSpeedtMilesn");
//print header

for (int day = 1; day <= 20; day++){
//run loop untill we pass day 20

    distance += speed * 24;
    //add speed*hoursInADay (=distance traveled that day) to distance 

    System.out.print(day + "t" + day*24 + "t" + speed + "t" + distance + "n");
    //print: day    hours   speed   distance

    speed++;
    //increment speed with 1
}

It works but in the solution you gave us the distance traveled jumps from 5544 to 488 from day 4 to 5, is this a mistake or?

We are here to answer your question about How can I create a loop that calculates the distance traveled using Java? [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji