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));
Related
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));
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.
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');
}
I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}
I an working on a project for an Introductory Programming class so I'm using basic javascript. This is our first project with functions and for some reason I can't seem to make it work. I called all my variables and created the function before the program starts but for some reason it skips over running the function in my program. Any help would be appreciated.
This is just the beginning of my program, I don't wanna write the rest of the code until I figure out why this part is broken, thats why the program doesn't do anything but close the window if it doesnt pass the tests.
// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";
function treeFunction(answer, counter, numTrees) {
while (answer == "no" && counter < 3) {
if (numTrees == 5, 10) {
answer = "yes";
} else if (numTrees < 5 || numTrees > 10) {
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
counter + 1;
}
}
if (answer == "no") {
alert("You have entered an incorrect number too many times.\nThe Program will now end.");
window.open('', '_self', '');
window.close();
} else if (answer == "yes") {
return;
}
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees); {
document.write("<br/> <br/>" + "End of Program.");
}
You have;
if(numTrees == 5, 10)
The erroneous comma is causing the if to evaluate the truthy expression 10 so its always passing the test, to test for 5, 6, 7, 8, 9 or 10;
if(numTrees >= 5 && numTrees <= 10)
The way you are using the comma in this line has a special meaning:
if(numTrees == 5, 10)
Essentially what this does is returns the value of 10 (the second operand) when cast to a boolean, which is not 0, so it is true.
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comma_Operator
You probably meant to use OR (||):
if(numTrees == 5 || numTrees == 10)
Or check numTrees against a range:
if(numTrees >= 5 || numTrees <= 10)
On a side note, in javascript it is recommended that you always use identity comparison (===) instead of regular comparison (==):
if(numTrees === 5 || numTrees === 10)
if(numTrees == 5, 10) doesn not mean If numtrees is equal to 5,6,7,8,9, or 10
change it to
if(numTrees >= 5 || numTrees <=10)
if (numTrees == 5, 10) {
answer = "yes";
}
This is an odd-looking construct that I've never seen before. I'm assuming you believe it means "is numTrees within the range 5 to 10?", but that's not the case. Without checking, I think it essentially means you're checking two things at once:
is numTrees equal to 5?
is 10? (this essentially means "is 10 not 0", which of course is always true).
Since the 2nd condition you're checking is always true, you're always setting answer to "yes". As a result, your loop always runs exactly once - it starts up, checks answer is "no", sets answer to "yes", and that immediately stops the loop.
You need to change your condition to if(numTrees >= 5 && numTrees <= 10)
What you want is something more like this:
if (numTrees < 5 || numTrees > 10) {
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
counter + 1;
} else {
answer = "yes";
}