This question already has answers here:
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 1 year ago.
Pretty straight-forward what I want to do:
If the input is 0, it means that they didn't input a number and it
should tell you so.
When the input is 7, it should say that you got it right.
Anything else, it should tell you that you got it wrong.
But it just outputs the "7 is correct" line no matter what the input is, and I can't figure it out what is wrong.
<script type="text/javascript">
function problem2 ()
{
var number = 0;
var text=document.getElementById("output");
number = prompt("Enter a number between 1 and 10 please" , 0);
if (number = 0)
{
text.value = "You didn't enter a number!";
}
if (number = 7)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
}
</script>
<input type="button" value="Click here" onclick="problem2()">
<input id="output" type="text">
You're assigning with =. Use == or ===.
if( 0 == number ){
text.value = "You didn't enter a number!";
}
Also, be wary of your brace placement. Javascript likes to automatically add semicolons to the end of lines. Source.
You are using assignment operators as your conditionals instead of comparison operators:
if (number = 0) // falsy. Same as if (false)
{
text.value = "You didn't enter a number!";
}
if (number = 7) // truthy. Same as if (true)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
Alternatively you can use a switch and organize the conditionals a bit easier:
switch (number) {
case 0:
text.value = "You didn't enter a number!";
break;
case 7:
text.value = "7 is correct!";
break;
default:
text.value = "Sorry, ", input, "is not correct!";
break;
}
Here is a code with the some fixes and improvements (I commented what I changed):
function problem2 (){
//I multiplied by * 1 to work with numbers, also used || to default to 0 in case of NaN
var num = (prompt("Enter a number between 1 and 10 please" , 0) * 1) || 0;
var msg = "";
if (!num){ //I prefer this over 'num == 0'
msg = "You didn't enter a number!";
//you should use 'else if' in this case
}else if (num == 7){//'=' is for assignment, use '==' or '===' instead
msg = "7 is correct!";
}else{
//you had an undefined var 'input', you probably meant 'num'
//you also were connecting var and strings using commas, use '+' instead
msg = "Sorry, " + num + " is not correct!"; //added a space in ' is'
}
//no need to store the element in a var anymore :D
document.getElementById("output").value = msg;
}
Aditionally, two more changes can be made:
only one var (e.g var something = "", somethingElse = 99;)
assign the default text from the beginning, like var msg = "default" and remove the else
Note: an undocumented change I made was to rename some vars, I encourage everyone to stop using vars like number, text, string, if you have this bad habit, you will eventually use illegal var names by mistake.
Related
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
I'm new to js/programming and just making a simple calculator using prompt. I'm trying to validate that what's been entered are numbers and not strings. I tried this
var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();
switch (operatorType) {
case 'add':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
if (isNaN(i) === false) && (isNaN(j) === false) {
document.write(i+" plus "+j+" equals "+(i+j));
} else {
document.write("You didn't enter two numbers.");
}
break;
As well as if (i != 'string') && (j != 'string') but I keep getting "Unexpected token &&". I looked it up and if/else within a case is valid so I'm not sure what I'm doing wrong.
Full code if it helps
var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();
switch (operatorType) {
case 'add':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
if (isNaN(i) === false) && (isNaN(j) === false) {
document.write(i+" plus "+j+" equals "+(i+j));
} else {
document.write("You didn't enter two numbers.");
}
break;
case 'subtract':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" minus "+j+" equals "+(i-j));
break;
case 'multiply':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" multiplied by "+j+" equals "+(i*j));
break;
case 'divide':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" divided by "+j+" equals "+(i/j));
break;
default:
document.write("Please enter whether you want to add, subtract, multiply or divide.");
break;
}
You have your parenthesis in the wrong spot causing the syntax error. You need to move the parenthesis in this line to change from:
if (isNaN(i) === false) && (isNaN(j) === false) {
So that it becomes:
if (isNaN(i) === false && (isNaN(j) === false)) {
You'll also need to convert the strings to numbers so that your code truly adds/etc instead of concatenates the text.
I'm trying to write some javascript code that asks the user to guess a number from 1 to 1000 and enter it into the prompt box. If the user guesses right, an alert box will pop up saying they got it right. If they guess wrong, another alert box will popup and say that they are wrong and to try once more.
The issue here is that I don't know what I have to do to make the code loop infinitely until they get the right answer. Here's what i have so far:
var a = 489; // the number that needs to be guessed to win the game.
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
Number matching
Basically, when you make prompt, it returns a String or text, not a number. To fix this, do:
if (parseInt(b,10) === a) {
//Code
}
Other ways
They're a lot of ways to parse numbers. Here's a few more:
parseFloat(b); // Also parses decimals: '5.3' -> 5.3
parseInt(b, 10); // Gives an integer (base 10): '5.3' -> 5
+b; // A very 'short' way; '5.4' -> 5.4
Number('5.4e2'); // Number case: '5.4e2' -> 540
Looping
Now to repeat? Make it a loop!
var a = 432;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a){
alert("You're right!");
break; // Stops loop
} else if (!b) { break; }
else {
alert("Incorrect! Try again!");
}
}
Not sure why, but some people hate while true loops. They shouldn't cause any problems as long as you coded it properly
Random Numbers
You can get a random number using Math.random.
var min = 1,
max = 1000;
Math.floor(Math.random() * (max - min + 1)) + min;
If you're like me and want short code, you can shorten it by:
Math.floor(Math.random() * (999)) + 1;
All Together Now!
var a = Math.floor(Math.random() * (999)) + 1;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
break; // Stops loop
} else if (!b) {
alert("The Correct Answer was: " + a); //Shows correct answer
break;
} else {
alert("Incorrect! Try again!");
}
}
Just stick your prompt in some kind of loop. The code will inside the loop will run over and over until the comparison is false.
Basic example:
http://jsfiddle.net/s2he1twj/
var a = 500,
b;
while (parseInt(b) !== a) {
b = prompt('Enter a number!');
if (b === null) break;
}
while loop
Do this recursively by calling the same function like
var a = 489;
function promptGuess(){
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a){
alert("You're right!");
} else {
alert("Incorrect! Try again!");
promptGuess();
}
}
promptGuess();
Use a while until the match:
var a = 489;
var b;
while(b != a) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
}
One more thing: although the b != a evaluation is correct, it's error-prone. The != operator do conversion type, whilst the !== operator compares types and value.
In your case: 5 != '5' will return false, but 5 !== '5' returns true. It's recommended that your comparisons be conversion-free. It's more strict.
In your case, this means:
while(parseInt(b) !== a)
Greetings!
I am working on a zodiac calendar that requires a switch 0-11 for the signs. I have written HTML code that drops down for the month and a text input for the year. The sign should use id 'output' and should also show up in text. I am not sure if I am using my switch correctly, of if my math is causing the problem or why it is not sending to output.
HTML CODE:
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
Javascript Code
if (year && year.value && (year.length == 4)){
year = parseInt(years.value);
month = parseInt(month.value);
if (month < 2) {
year = (year - 1);
}
year = ((year - 1924) % 12);
} else { // Show Error:
document.getElementById('year').value =
'Please enter valid values.';
}
switch (year){
case 0 :
block code;
break;
etc..
} // End Switch
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
return false;
}
Your regular expression could be failing to match your lowercased url. When that happens, the result would be null.
You should be checking the match() result before using it. Something like this:
var matches = url.toLowerCase().match(/https?:\/\/(.+?)[?#\/$]/);
if (!matches || matches.length < 2) {
// Handle error
...
} else {
// Keep going
var domain = matches[1];
...
}
Also, verify that your regular expression is actually doing what you intend.
Because of my javascript code innerText
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
I had to delete
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
and replace it with
<p>Sign: <span id="output"></span></p>
I could have easily changed the javascript code and document.getElementID('output') = sign.value;
The problem should be caused by domain checking instead of calculate function.
Remove domain checking and try again (see if it works).
Errors:
1) if (year && year.value && (year.value.length == 4)){
year = parseInt(year.value);
2) main html didn't declare element "output"
I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/