0
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

Kropotkin
  • 353
  • 3
  • 10
  • If you're using node, consider using [readline](https://stackoverflow.com/a/68504470/989920) instead of `prompt`.? – evolutionxbox Aug 16 '23 at 13:22
  • 1
    Dunno if this helps but you can remove the X from the array as well `arr = arr.filter(item => item !== 'X')` – Chris G Aug 16 '23 at 13:24
  • _"I think this is something about 'pre-conditions' and 'post conditions'?"_ - not really. Whether you change the condition into something else, or make it a while instead of a do-while loop - won't change the fact, that you are pushing the latest input to your array, _before_ the check will happen. With those two operations, the prompt and the push, directly after each other, it _can't_ behave any different. You need to _somehow_ implement the check _between_ those two. – CBroe Aug 16 '23 at 13:27
  • @CBroe - thanks, I see, – Kropotkin Aug 17 '23 at 07:59
  • @evolutionxbox - Can you say why you suggest using readline instead of prompt? ( i choose prompt because readline seems to involve some boilerplater and this is for a tutorial so I wanted to keep it as simple as possible) – Kropotkin Aug 17 '23 at 08:00
  • 2
    @Kropotkin because there is no `prompt` in nodejs (unless you installed some additional package) – derpirscher Aug 17 '23 at 08:05

2 Answers2

3

The following should work - Assuming you want only integers saved to the studentAges array:

// Valid age range ...
const k_age_min = 1;
const k_age_max = 100;

// Terminate when this is entered by the user ...
const k_terminate_token = 'X';

// Age prompt ...
const k_age_prompt = 'Enter an age (' + k_age_min + '-' + k_age_max +'); enter ' + k_terminate_token + ' to finish: ';

let age;
let input;
let studentAges = Array();

// Initial read ...

input = prompt( k_age_prompt );

// Loop until done ...

while ( input !== k_terminate_token ) 
{

   // Make sure input is a number ...
   
   age = parseInt( input );
  
   if ( Number.isFinite( age ) )
   {
   
      // Include age range check ...
      if ( age >= k_age_min && age <= k_age_max )
      {
         studentAges.push( age );
      }
      else
      {
        console.log( '* Age must be between ' + k_age_min + ' and ' + k_age_max );
      }
      
   }
   
   input = prompt( k_age_prompt );

}

console.log( studentAges );
bdcoder
  • 3,280
  • 8
  • 35
  • 55
  • From where do you draw the conclusion, that OP wants to stop inputting at any non numeric input? And if we are talking about data-validation (you seemingly are), what about negative inputs? What about inputs > 1000? – derpirscher Aug 16 '23 at 14:21
  • True - I am making the assumption (looking at the OP code) that they only want student ages (numeric values) in the "studentAges" array. Kropotkin - please update your question if that is NOT the case. Also true - I did not include a check for "negative" ages or ages > 1000 (which can be included with a simple if statement to validate age range). – bdcoder Aug 16 '23 at 14:29
  • @Kropotkin - Is that the correct assumption? That you only wanted numeric values in the "studentAges" array? If so, I have also added a range check to my answer as per derpirscher comments. – bdcoder Aug 16 '23 at 14:46
  • @btcode - you understood correctly. I just want numbers/ages. Your code improves on mine in that I would have allowed e.g. 'Z' to end up in the array. As for the loop, I now understand as per Cbroe ;s comments above that I can't do what I want to do and have to have a check just before the push into the array. – Kropotkin Aug 17 '23 at 08:05
  • 1
    @Kropotkin - Glad to hear / help - also updated the code to include some constants that would make the code easy to modify in the future. – bdcoder Aug 18 '23 at 01:38
0

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:

let input;
let studentAges = [];

console.log("Enter an age or X to finish");

do {
  input = prompt('Enter age ');
  if (input !== "X") {
     studentAges.push(input);
   }
} while (input !== "X");

console.log(studentAges);

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.

Aziz Saidi
  • 11
  • 3
  • This will not work - If the user enters any non-numeric such as "A", it will be included in the array. – bdcoder Aug 16 '23 at 13:51
  • Thanks Aziz. Yes. This will work and is what I will do if I can't fix the loop problem. But I wanted to do it so the loop would exit as soon as 'X' is entered without executing the code in the loop. So - this fix is ok but not a direct answer to my question. I am assuming an integer or X so it doesn't matter about other non integer input. – Kropotkin Aug 17 '23 at 07:57