Active Coder
Active Coder

Reputation: 111

How to use loop in JavaScript using while?

please excuse my ignorance; I am learning JavaScript from scratch with no background in coding.

Here is the question: Define three variables for the LaunchCode shuttle---one for the starting fuel level, another for the number of astronauts aboard, and the third for the altitude the shuttle reaches.

Construct while loops to do the following: Prompt the user to enter the starting fuel level. The loop should continue until the user enters a positive value greater than 5000 but less than 30000. I am very confused by the question, can you please explain it to me?

Use a second loop to query the user for the number of astronauts (up to a maximum of 7). Validate the entry by having the loop continue until the user enters an integer from 1 - 7.

Use a final loop to monitor the fuel status and the altitude of the shuttle. Each iteration, decrease the fuel level by 100 units for each astronaut aboard. Also, increase the altitude by 50 kilometers. (Hint: The loop should end when there is not enough fuel to boost the crew another 50 km, so the fuel level might not reach 0).

After the loops complete, output the result with the phrase, The shuttle gained an altitude of ___ km.

If the altitude is 2000 km or higher, add "Orbit achieved!" Otherwise add, "Failed to reach orbit."

And here is my code for the question to answer first part:

  const input = require("readline-sync")

let startingFuelLevel=0;
let numberAstronautsAboard =0;
let altitudeshuttleReaches =0;

//a:
while (startingFuelLevel <= 5000 || startingFuelLevel >30000){
     startingFuelLevel = input.question("Enter the starting fuel level: ")
};

//b:
while(numberAstronautsAboard < 1 || numberAstronautsAboard > 7){
  numberAstronautsAboard = input.question("Enter the number of astronauts: ")
}

Upvotes: 0

Views: 239

Answers (1)

Darius
Darius

Reputation: 61

JSFiddle (pure js): https://jsfiddle.net/DariusM/14parbue/18/

Apart from the messages, a condition and a check for isNaN, it seems that you got the first two parts somewhat right - the user input.

As for the third loop, you can use setInterval() to run a function repeatedly, each time doing the following:

  1. decrease fuel level
  2. increase altitude
  3. check if there is enough fuel for another iteration.

Depending on the check at (3) above, you can then show a certain message to the user depending on the current altitude.

Then, after the fuel is finished and the final message is displayed to the user, the interval needs to be cleared using clearInterval()

Good luck with your endeavor and happy coding!

Upvotes: 1

Related Questions