JS: Validate integer/user input with validation loop and prompt - javascript

I am writing a number guessing game. The guessing game starts by prompting a user for a maximum number (this is not their guess yet--it's the top range for their guess). The prompt should be in a loop with validation, making sure the max number is a (rounded) positive integer. The loop should reprompt the user if the input is 0, <0, or a non-number. I am having trouble getting the validation loop to work.
This is what I have so far, and the prompt works, but the function does not work as I need it to.
let suggestion = parseInt(prompt("Help me come up with a range from 1 to a higher number. Type in a number greater than 1."));
function get_suggestion(prompt) {
let validInput = false;
let initial_ans, input;
while(!validInput) {
input = window.prompt(prompt);
initial_ans = parseInt(input);
if(initial_ans != NaN && initial_ans > 0) {
validInput = true;
message.innerHTML = "Guess a number!"
}
}
return(initial_ans);
}

Related

A banking function that loops user input and increments/decrements until exit key is entered in js

I am trying to write a function that gives a user 4 choices, does what they choose and then asks them the first 4 choices again and again until they exit.
I have tried using an if/else loop inside a while loop, but that just takes the first user input and loops at that point. It also concatenates the balance when I try to add the two numbers. I assume that due to the fact that the prompt is a string and assigns a string to the variable. I am using console.log() to try and see what is happening while everything is running, but to no avail.
Sorry if this is a lengthy post and redundant.
let balance = 0;
let deposit = 0;
let withdraw = 0;
function bankFunction (banked) {
alert('Hello, how can I help you today?');
let input = prompt('Q to quit the application \nW to withdraw \nD to deposit \nB to view balance');
while (input != 'Q') {
if (input === 'W') {
withdraw = prompt("Withdraw how much?");
console.log(withdraw);
balance = balance - withdraw;
console.log(balance);
} else if (input === 'D') {
deposit = prompt("Deposit how much?");
console.log(deposit);
balance = balance + withdraw;
console.log(balance);
} else {
alert("done");
break;
}
}
}
If you want to continuously prompt the user for inputs, then the prompt function should be inside your loop too. The essential pseudo code is: "While the input is not "Q", continue to prompt for a user choice".
Implementation:
let input = "A" // Initial input to get the loop working
while (input !== "Q") {
// Get actual user input
input = prompt("Choose Q or W or D or B");
if (input === "W") {
// Withdraw logic
}
else if (input === "D") {
// Deposit logic
} else if (input === "B") {
// ...
}
}
Note that there is a bit of a little gimmick here: I needed to have an initial input ("A") to get the first round of the loop working - since in the first round of the loop, user input has not been received yet. Once it get past that initial first round, the input variable is being continuously re-assigned through the user prompt, and the loop will exactly how the pseudo-code described it.
If you don't like that gimmick, there is another way, called the While-True-Break loop. The essential idea is that: The loop will automatically run forever, until you explicitly stop it (via break statement)
let input;
while (true) {
input = prompt("Choose Q or W or B or D");
if (input === "Q") {
// Stop the program loop
break;
} else if (input === "W") {
// ...
} else if ...
}

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

Trying to sanitize input with isNaN method, but it crashes the while loop

I am attempting to code for a project that requires me to prompt the user to input a number. I have the code set up so it accepts only numbers and operates on them, but it doesn't sanitize the input until the end. I tried using an inNaN method and a while loop to keep the code going until the user enters a real number, but when it identifies NaN, it crashes. Here's my code below:
var userMin = Number(prompt("Name a minimum number to begin your range.
Only numbers, please.")); //This is the prompt that asks for the number
var repuserMin = true; //This is the beginning of the while loop
while (repuserMin){
if (isNaN(userMin)) {
repuserMin = true; //Where the if statement glitches, JSFiddle crashes at this point
} else {repuserMin = false;}}
You need to change userMin inside of the loop, by prompting the user to update the value if their entry is not a number:
var userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
var repuserMin = true; // Trigger the loop by default
while (repuserMin) {
if (isNaN(userMin)) {
userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please."));
} else {
repuserMin = false; // Break out of the loop
console.log('Number was entered');
}
}
Yes it will crash because you are trying to run a infinite while loop there.
You need to take the input from the user every time inside the loop.
var repuserMin = true; //This is the beginning of the while loop
var userMin;
while (repuserMin) {
userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
if (isNaN(userMin)) {
repuserMin = true; //Where the if statement glitches, JSFiddle crashes at this point
} else {
repuserMin = false;
}
}
EDIT
You need to handle the case where the user will not enter anything.
isNaN('') --> false
while (true) {
var userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
if (!isNaN(userMin) && userMin) {
break;
}
}

How to let an input form have multiple outputs?

I am trying to make a form that someone can enter a number and each number entered will correspond to a certain value in the output text. What I have so far is this:
<script>
function myFunction() {
var x, text;
x = document.getElementById("zip").value;
if (x = 53527) {
text = "$20.00";
}
if (x = 53718) {
text = "$25.00";
}
else {
text = "Please Call for Delivery";
}
document.getElementById("fee").innerHTML = text;
}
</script>
Overall it works, but the problem that I am having is once a number is entered, it always displays the "$25.00" value no matter what is entered in. I am not sure what is making it override the other values. Any help would be great. I am new to this and learning it as I go.
Change the single equal signs on (x = 53527) and (x = 53718) to double equal, i.e. (x == 53527) and (x == 53718) and see if works. Because in javascript when you are comparing values inside an if you have to have double equal.
Pay additional attention with your else clause because this is acting only over your second if. If you want to use it as an else for both ifs you can use else if on your second if.

Have been scanning for NaN and getting lost

I am defining a function that takes three numbers as arguments and returns the largest of them.
Here is my code:
var instructions = alert("Choose a set of numbers to input for the computer to determine which value is the largest");
var inputOne = prompt("Please input your first desired value");
var inputTwo = prompt("Please input your second desired value");
// THIS ARRAY STORES THE VALUES OF inputOne && inputTwo
var maxInput = Math.max([inputOne, inputTwo]);
var inputThree = prompt("Please input your third desired value");
// THIS WILL COMPARE BETWEEN THE inputThree && THE MAX INPUT OF THE USERS FIRST TWO CHOICES
var maxNumber = Math.max(maxInput, inputThree);
//validate if inputs are numbers and not letters
// isNaN()
var compare = function (maxNumber, inputThree) {
if (inputThree === maxNumber) {
return alert("The result is the same!");
} else if (inputThree != maxNumber) {
return alert(maxNumber + " " + "is the larger value!");
}
}
compare(maxNumber, inputThree);
Now I'm getting a result of "NaN is the larger value!" and it's driving me crazy! I tried running console.log to see where I'm getting NaN but that didn't work at all. All that did was log NaN to the console.
I also tried taking the parameters out of Math.max( ) however was just getting:
"-infinity is the larger value!"
Can someone at least give me a hint as to why this is happening? Or explain to me further what is going on.
Math.max([inputOne, inputTwo]) should be Math.max(inputOne, inputTwo)
Why don't you just get the largest of all of them with just
var maxNumber = Math.Max(inputOne, inputTwo, inputThree);
Here:
var inputThree = prompt("Please input your third desired value");
inputThree is a String (i.e. its value has a Type of String), always. And here:
var maxNumber = Math.max(maxInput, inputThree);
maxNumber is a Number, always (because that's what Math.max returns, even though the arguments are Strings). So:
inputThree === maxNumber
is always false, because a Number is never equal to a String (see the Strict Equality Comparison Algorithm). So either convert inputThree to a Number, e.g.
+inputThree === maxNumber
or use ==.
inputThree == maxNumber

Categories