skip to Main Content
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


  1. 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.

    Login or Signup to reply.
  2. 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:

    1. check the value before you push

      if (input !== "X") array.push(input)
      
    2. rewrite your loop from do { ... } while (..) to while (..) { ...}

       let input;
       while ((input = prompt(...)) !== "X") {
          array.push(input);
       }
      

    Or a different approach: Just remove the last element once the loop is done

    array.splice(-1, 1)
    

    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 …

    Login or Signup to reply.
  3. The following will work – Note the loop will exit when any non-Numeric is entered:

    let input;
    let studentAges = Array();
    
    console.log("Enter an age or X to finish");
    
    input = parseInt( prompt('Enter age: ' ) );
    
    while ( Number.isFinite( input ) ) 
    {
        studentAges.push(input);
        input = parseInt( prompt('Enter age: ' ) );
    }
    console.log(studentAges);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search