let input;
let studentAges = Array();
console.log("Enter an age or X to finish");
do
{
input = prompt('Enter age ');
studentAges.push(input);
} while ( input !== "X")
console.log(studentAges);
This is node, and input is entered on the console.
The problem is that the array includes the ‘X’. E.g. I end up with [10, 12, 14, ‘X’]
How can I stop before the ‘X’? I could just test for the X and not push it onto the array. But I’d like to keep this simpler. I think this is something about ‘pre-conditions’ and ‘post conditions’?
Thank you
3
Answers
You’re right that this issue can be addressed by changing the logic inside your loop. One way to achieve this is by adding a conditional check before pushing the input onto the array. Here’s how you can modify your code to stop before adding ‘X’ to the array:
This code snippet checks whether the input is equal to "X" before adding it to the studentAges array. If the input is not "X", it gets added to the array. This way, the ‘X’ value will not be included in the final array.
The crucial point is: you are pushing to the array unconditionally, once you have read the input. This is is wrong. You must do a check after reading but before pushing.
There are multiple ways to accomplish this:
check the value before you push
rewrite your loop from
do { ... } while (..)
towhile (..) { ...}
Or a different approach: Just remove the last element once the loop is done
Notice: Still using your
prompt
here, eventhogh that’s not valid for nodejs. See @evolutionbox comment about using readline on how to make this work with node …The following will work – Note the loop will exit when any non-Numeric is entered: