Do while loop until user enters valid input - javascript

I need to create a do while loop that accepts any user input until a number is entered. my loop doesn't execute as expected. please help.
can i do without the maximum and the minimum values?
var number;
var minimum = 1;
var maximum = 20
window.prompt("Please enter a number between 1 and 20");
do {
if (number >= minimum && number <= maximum)
break;
else(window.prompt("Invalid input, please enter a number between
1 and 20 "));
}
while (number < minimum || number > maximum);

The code below works for you.
It's basically the same as yours, but I made it much more efficient and readable.
A few things I changed for you was:
window.prompt and prompt do the same thing. In other words, the window is unnecessary typing, so use just prompt.
prompt alone just asks for an input. It doesn't store it anywhere, or do anything with it. For you to be able to do anything with it, you need to set the value of a variable to equal it. I set number to equal the prompt
You can use isNan() to check if it is a string or a number.
var number = prompt("Please enter a number between 1 and 20");
var minimum = 1;
var maximum = 20
do {
if (isNaN(number)) {
break;
}
else {
number = prompt("Please enter a valid number between 1 and 20");
}
}
while (!isNaN(number));

Related

Javascript:How to break a while loop when a condition is met to make it so that the loop is terminated when a Var is not null (Break Not Working

var Age;
Age = prompt("How old are you");
while (Age === null){
prompt("Please Cofirm You Name");
if (Age > 0 ){
break;
}
}
I am trying to make it so that the user is in a loop until var Age is not null... My goal is to make it so that you cant cancel the prompt and have to type in it. I have tried using the break; in an if statement but its not working.
When I use the break; in an if statement it continues to send the prompt
Is there another way to do this
Or is the value of var Age equal to null(even if you add an integer greater then 0) for some reason and if it is anyone know how to fix it
is there are better way to make to user type in the prompt
Thank You in advanced
var Age = prompt("How old are you?");
Age = Number(Age);
while (isNaN(Age) || Age < 1) {
Age = prompt("Please confirm your age.");
Age = Number(Age);
}
In the prompt dialog box, the user can enter anything. So we are trying to see if the user has entered a number by using Number(Age) which tries to parse the user entered value as a number, and returns a number if it is a number.
That means if the user entered value is number, then Age will have a valid number (but it might be negative, which is invalid for our use case). Anything other than a number will give either NaN or 0.
So, when you write Age = Number(Age),
Age might be assigned with a proper number (positive or negative), or
NaN (NaN stands for not a number and it is considered a type of
data in JS), or
0 when user enters space(s).
In the while loop condition, we are checking whether the user entered value is invalid. That is, is Age not a number? or is Age less than 1?.
The || operator used between these two conditions will return true if any one of these two conditions is true (in fact, if the first condition is true, it doesn't even bother to check the second condition, and simply returns true). It returns false if both of the conditions are false.
So, if the user has entered invalid input (negative number or space or string), we prompt the user till he enters a proper value.
A while-loop has a break, look at this simple example.
let a = 2;
while (a <100) {
console.log(a);
a *= 2;
if (a===16)
break;
}
Try with do-while:
let age, age2;
do {
age = prompt("How old are you?");
} while (age === "");
do {
age2 = prompt("Please Cofirm Your age");
} while (age2 === "" || age2 !== age);

How can I count the number of digits of a number with leading zeros in javascript?

I am taking a field value, that should be a 4 digit number.
I want to make sure that the value is a 4 digit number and if not, have a pop up that says "enter a 4 digit number".
I noticed that when I put the field value into a variable it does not take any of the leading zeros. The last test case I ran the code with was a value of '0000'.
var relay = this.getField("RELAY NUM").value;
var relayString = relay.toString();
var relaySplit = relayString.split("");
console.println("relay= " + relay);
console.println("string= " + relayString);
console.println("split= " + relaySplit);
for(i = 0; i < 4; i++){
if (relaySplit[i] >= 0) {
console.println("Looks good so far");
} else {
console.println("Please enter 4 digit number");
}
}
--------------------------------------------------------
relay= 0
string= 0
split= 0
Looks good so far
Please enter 4 digit number
Please enter 4 digit number
Please enter 4 digit number
true
Instead of traversing arrays, an approach you may want to consider is using a regex to determine whether the input value meets your criteria. Then on events such as keyup (using jQuery here but not necessary), you run the validation and apply styles, or send forth the popups as you wish. I put a limit on the length of the input so users are not able to enter MORE then expected input, but this isn't necessarily needed.
$("#input").keyup(function() {
let input = $("#input").val()
let isValid = validate(input)
$("#val").text(isValid ? "Valid" : "Invalid")
})
function validate(val) {
let x = /^[0-9]{4}$/
return x.test(val)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="input" maxLength="4" />
<label id="val"></label>
</div>

Problem when validating numbers 1, 2, and 3

I'm currently working on an assignment where a person must choose cave 1, 2 or 3. Everything works except the validation part. This function is used to see if the user put in a number lower than 1, higher than 3 or not even a number. I'm trying to use a while loop to fix my problem. I have tried putting a continue after between the third last and second brackets.
//Gets input from the user
guess = prompt("Which cave will you go in? 1, 2 or 3?");
valid(guess);
//Checks if the input is valid
function valid(number) {
while(isNaN(number) || number < 1 || number > 3){
alert("Please Try Again");
prompt("Which cave will you go in? 1, 2 or 3?");
if(number <= 1 || number >= 3){
break;
}
}
}
You need to store the second prompt return value in a variable.
Also, return value of prompt is always a string, so you need to parse it into an int too for proper comparison, although JS implicitly converts it for you.
//Gets input from the user
guess = parseInt(prompt("Which cave will you go in? 1, 2 or 3?"));
valid(guess);
//Checks if the input is valid
function valid(number) {
while(isNaN(number) || number < 1 || number > 3){
alert("Please Try Again");
let number = parseInt(prompt("Which cave will you go in? 1, 2 or 3?"));
if(number <= 1 || number >= 3){
break;
}
}
}
You are not storing the prompt input in the function. Here is the solution with some modifications:
//Gets input from the user
guess = prompt("Which cave will you go in? 1, 2 or 3?");
valid(guess);
//Checks if the input is valid
function valid(number) {
let guess = number;
while(isNaN(guess) || guess < 1 || guess > 3){
alert("Please Try Again");
guess = prompt("Which cave will you go in? 1, 2 or 3?");
if(!isNaN(guess) && guess <= 1 && guess >= 3){
break;
}
}
}
change this line valid(guess); to valid(parseInt(guess));

I want to put validation for the prime Number Program

If the user enters nothing in the prompt box then also it is showing "The num is prime", I have put validation below. Also if I enter "1" in prompt box, it is still showing "The num is prime".
var Num = prompt("Enter the Number");
var flag = 0;
if (isNaN(Num)) {
alert("please enter valid number");
}
for (var i = 2; i < Num; i++) {
if (Num % 2 === 0) {
flag = 1;
break;
}
}
if (flag === 0) {
alert("The num is prime");
}
else if (flag === 1) {
alert("The num is not prime");
}
Annoyingly, isNaN("") returns false, as if "" were a number. To fix the problem with the empty prompt, you're gonna need to check that Num.length > 0
The isNaN function is not intended to be used to check whether or not something can be interpreted as a number. It's intended to check if the provided value is the specific NaN value. My suggestion would be to attempt to convert the prompted string into a number and see if that conversion was successful.
var Num = parseInt(prompt("Enter the Number"), 10);
if(Number.isNaN(Num)) {
alert("please enter valid number");
}
Please note: this will not ensure that all provided values will be valid. For example, parseInt("ABC123") will return NaN as expected, but parseInt("123ABC") will return 123 and ignore the subsequent "ABC".
Regarding the issue with 1s, the code you have provided appears to mark all odd numbers as prime. Assuming you have written the part that determines whether or not an odd number is prime, you could have a special case to say "if the number is 1, it's not prime." That's because for many purposes, 1 acts like a prime number. Obviously, it's not the most elegant solution, but... it works.

Javascript user input validation

My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}

Categories

Resources