简体   繁体   中英

While loop for odd or even

Ask user for a number. Determine if the number is even or odd. I have my constants set and using modulo to figure this out. However I am stuck in an infinite loop and can't figure out why. I have my if statement in the loop as well as a break statement to get out, but still in an infinite loop.

HAVE TO USE A WHILE LOOP

 // declare constants const MODULO = 2; const EVEN = 0; const ODD = 1; // declare variables var enteredNumber; var result; // prompt user to enter an even number enteredNumber = prompt("Enter an even number: "); // convert user input into a number enteredNumber = Number(enteredNumber); // determine result of modulo equation result = enteredNumber % MODULO; // while loop to check if enteredNumber is even or odd while (result === EVEN) { document.write(enteredNumber + " is an even number <br/>"); enteredNumber = prompt("Enter an even number: "); enteredNumber = Number(enteredNumber); result = enteredNumber % MODULO; if (result === ODD) { document.write(enteredNumber + " isn't an even number"); break; } }

You can essentially one-liner this thing. You're already checking stuff with the while .

 document.addEventListener('DOMContentLoaded', () => { while (!(parseInt(window.prompt('Enter an even number', '2') || '1', 10) % 2)) { }; });

Why this works

Javascript has 'falsy' and 'truthy' values.

window.prompt('Enter an even number', '2')

This code prompts the user for a number. The result is a string (or null, if the user blanks out the prompt).

<a string or null> || '1'

If the user blanked out the prompt, it will return null . In Javascript we can use the or operator to choose between two things. null || '1' null || '1' reads from left to right. The first thing is falsy so it chooses '1' .

If the user entered a number (like 10), we would get the number they entered as a string.

Then we parse the string to a number with parseInt .

Take that result and use the modulo operator % to divide by the operand and return the remainder . When you divide by 2 the remainder will either be 0 or 1 . These are falsy/truthy values.

while(0) evaluates to false and breaks the loop. while(1) evaluates to true and continues the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM