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 3 days ago.
I have this javascript code that is not working. Althought the first conditional(if conditional) is working, the else conditional is not working. Sorry for my bad english.
function choice1()
{
if(pic_location<9)
{
if(document.getElementById("choice_1").value==character[numbers[pic_location]])
{
window.alert("Guess Correct!");
score = score + 1;
document.getElementById("score").innerHTML = score;
pic_location=pic_location + 1;
document.getElementById("pic").setAttribute("src", "pictures/" + character[numbers[pic_location]] + ".jpg");
}
else
{
window.alert("Wrong Answer!");
pic_location=pic_location + 1;
document.getElementById("pic").setAttribute("src", "pictures/" + character[numbers[pic_location]] + ".jpg");
}
set_choices();
document.getElementById("qn").innerHTML= pic_location + 1;
}
else
{
if(pic_location==10)
{
document.getElementById("choice_1").value==character[numbers[pic_location]];
window.alert("Guess Correct");
score = score +1;
window.location="game3.php";
}
else
{
window.alert("Wrong Guess!");
window.location="game3.php";
}
}
}
The if function is working fine when i run it but when I get to the last photo location which is 10, it always guesses wrong even though the answer is right.
Note: my function is the same for the four choices. They all have the same problems.
You are using comparison operator == instead of assignment =
if(pic_location==10)
{
document.getElementById("choice_1").value==character[numbers[pic_location]];
window.alert("Guess Correct");
score = score +1;
window.location="game3.php";
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Please help the green beginner beginner. I am programming a home calculator in js (so I'm not afraid of the terrible eval()) I fixed all (I hope so) errors, but unfortunately there is one that is difficult to fix (if at all possible), in general the eval() method in js and python thinks that: -1 ^ 0.5 = -1 (second way square root) how to fix this ??
found what the main problems were:
1st - it was impossible to write -1 ^ 0.5 (the (^) sign is not supported, only the (**) sign) - you need to indicate this in the instructions
2nd - it was impossible to write -1 ^ 0.5 ("-1" cannot be written, negative numbers must be enclosed in brackets (-1))
3rd - there was an error in this line of code: result = Math.round ((result + Number.EPSILON) * 100) / 100; it should be like this:
result = Math.round (result * 100) / 100; (some way of rounding to two decimal places)
I need to do the following:
• you need to complete the error message (alert - "You entered -1 instead of (-1)"
• indicate in the instructions that you cannot enter alphabetic and special characters
• sign (^) - not supported, only sign (**) - to raise a number to a power
• "-1" cannot be written, negative numbers must be enclosed in parentheses (-1)
I am explaining because it will be useful to someone too.
So with eval () everything works as it should, thanks to #GenericUser he directed me in the right direction to find the error, where I started digging after.
here is the code:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
// Calculating a mathematical expression
// Input mathematical expression (logic for text-box)
function mathematical_expression() {
$(document).ready(function() {
$('#secret_box').dialog({
modal: true,
autoOpen: true,
buttons: {
'Cancel': function() {
$(this).dialog('close'); },
'Accept': function() {
$('#mainForm input#target').val($(this).find('#secret_widget').val());
console.log('The «Accept» is pressed!-[1.14]');
$(this).dialog('close'); } } });
$('#button14').click(function() {
$('#mainForm input#target').val($(this).find('#secret_widget').val());
console.log("math expression = " + math_expression1);
console.log("math expression = " + typeof(math_expression1));
console.log('The «Accept» is pressed!-[2.14]');
// $('#secret_box').dialog('close');
}); }); };
// Binding the «Accept» button to the «Enter» key (14)
function clickPress14(event) {
if (event.keyCode == 13 && math_expression1 == $('#secret_widget').val()) {
$('#mainForm input#target').val($(this).find('#secret_widget').val());
console.log("math expression = " + math_expression1);
console.log("math expression = " + typeof(math_expression1));
console.log("The button «Enter» is pressed!-[3.14]");
$('#secret_box').dialog('close');
try {
result = eval(math_expression1);
result = Math.round((result + Number.EPSILON) * 100) / 100; } // more correct rounding to two decimal places
catch (SyntaxError) {
Syntax_Error();
console.log('Catch Error!'); }
console.log("result = " + result);
console.log("result = " + typeof(result));
super_dialog(); };
if (event.keyCode == 13 && math_expression1 != $('#secret_widget').val()) {
console.log("math expression = " + math_expression1);
console.log("math expression = " + typeof(math_expression1));
console.log("The button «Enter» is pressed!-[3.14]"); }; }
// value_immediately14
function value_immediately14() {
$(document).ready(function() {
math_expression1 = $('#secret_widget').val();
console.log("math expression = " + math_expression1);
console.log("math expression = " + typeof(math_expression1));
$('#button14').click(function() {
$('#mainForm input#target').val($(this).find('#secret_widget').val());
$('#secret_box').dialog('close');
try {
result = eval(math_expression1);
result = Math.round((result + Number.EPSILON) * 100) / 100; } // more correct rounding to two decimal places
catch (SyntaxError) {
Syntax_Error();
console.log('Catch Error!'); }
console.log("result = " + result);
console.log("result = " + typeof(result));
super_dialog(); }); }); }
// Secret result
function super_dialog() {
$(document).ready(function() {
alert("The result of your math expression: " + math_expression1 + " will be is - " + result);
function alert(alert_text) {
$("#super_dialog").show();
$("#secret_text").text(alert_text); }
$("#secret_close").click(function() {
$("#super_dialog").hide();
window.location.reload(); }); }); }
// Syntax_Error Alert!
function Syntax_Error() {
$(document).ready(function() {
alert("The characters you entered are completely"
+ "\ndifferent from the mathematical expression."
+ "\nSo come on already bro... Adios mi amigo!!!");
function alert(alert_text) {
$("#alert_dialog10").show();
$("#alert_text10").text(alert_text); }
$("#alert_close10").click(function() {
$("#alert_dialog10").hide();
window.location.reload(); }); }); }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
// Warning! Incorrect input!
//Warning! Incorrect input!
function warning() {
if (sum == 0 || period == 0 || percent == 0) {
alert_result8(); }
else if (sum == 0 && period == 0 && percent == 0) {
alert_result8(); }
else if (X == 0 || Y == 0 || P == 0) {
alert_result8(); }
else if (X == 0 && Y == 0 && P == 0) {
alert_result8(); }
else if (Z == 0 && N == 0) {
alert_result8(); } }
// Warning! Incorrect input! (alert-box)
function alert_result8() {
$(document).ready(function() {
alert("You entered either the first or the second number incorrectly,"
+ "\nor you entered both numbers incorrectly at once! You may"
+ "\nalso have entered zero or both numbers as zeros!");
function alert(alert_text) {
$("#alert_dialog8").show();
$("#alert_text8").text(alert_text); }
$("#alert_close8").click(function() {
$("#alert_dialog8").hide(); }); }); }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
In JavaScript, ^ is the Bitwise XOR operator. If you want to do exponentiation, you can use either Math.pow or ** operator.
console.log(2 ** 2);
console.log(Math.pow(3, 2));
I've made a game with JavaScript where a player can only guess a random number from 1 to 10 three times, each time the program reads a wrong answer it displays what should've been the right answer, and tells the player to try again, if the player gets the right answer the game displays a message saying You got it right. I've managed to make the program work, and apparently, everything seems to be fine, except for one thing, the program won't stop even after the player gets the right answer, it reads through all the statements until it reaches the end. How can I make it stop after the right answer?
var random = Math.floor(Math.random() * 10);
var random1 = Math.floor(Math.random() * 10);
var random2 = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10, you have 3 chances.");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
alert("Sorry, the correct answer was " + random);
window.prompt("Make a guess from 1 to 10, you have 2 chances left.");
}
if (answer == random1) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
alert("Sorry, the correct answer was " + random1);
window.prompt("Make a guess from 1 to 10, you have 1 chance left.");
}
if (answer == random2) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
alert("Sorry, the correct answer was " + random2);
alert("You've lost");
}
First and forement, the bug
You have a bug in your code. If you win on the first round, it will detect this successfully. On the second and third round, any victory will be purely coincidence.
The reason is because you do not assign the return value from window.prompt to answer every time you call it. So the value of answer never changes from one round to the next.
To fix this, you should replace
window.prompt(...)
with:
answer = window.prompt(...)
The "bad" fix:
Let's start with a very simple (but very bad) solution, and use it as a springboard to teaching better architecture design.
Your current code roughly looks like this:
if (win) {
// say you won
} else {
// say you lost
}
if (win) {
// say you won
} else {
// say you lost
}
if (win) {
// say you won
} else {
// say you lost
}
With all of the extra stuff cleaned up you can clearly see why it's going through all three iterations: the three if/else blocks are entirely unrelated and know nothing about one another. It runs one if/else block, then another, then another -- in order, every time.
The easiest fix is to make sure the later blocks only run if you lose. This is pretty easy to do, because we already know if you lost -- it happens when you didn't win!
if (win) {
// say you won
} else {
// say you lost
if (win) {
// say you won
} else {
// say you lost
if (win) {
// say you won
} else {
// say you lost
}
}
}
Or, using your random, random1, and random2 variables:
var random = Math.floor(Math.random() * 10);
var random1 = Math.floor(Math.random() * 10);
var random2 = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10, you have 3 chances.");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
}
else {
alert("Sorry, the correct answer was " + random);
answer = window.prompt("Make a guess from 1 to 10, you have 2 chances left.");
if (answer == random1) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
}
else {
alert("Sorry, the correct answer was " + random1);
answer = window.prompt("Make a guess from 1 to 10, you have 1 chance left.");
if (answer == random2) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
}
else {
alert("Sorry, the correct answer was " + random2);
alert("You've lost");
}
}
}
This is ugly, but will work.
Springboarding into better design
As you might imagine, adding 4 or 5 or 6 rounds to this game would get REALLY tedious. You'd have to type out even more if/else blocks, create even more random variables, and type out even more alert statements. To make it more annoying, all of these alert statements contain the same text!
There's a concept in software design called DRY (Don't Repeat Yourself). This means that if you have two identical lines of code, you can probably rewrite it to eliminate the duplication.
In your case, we can do this using a while loop to check if we've won the game or not:
var youHaveWon = false;
while( ! youHaveWon ) {
var random = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
youHaveWon = true;
}
else {
alert("Sorry, the correct answer was " + random);
}
}
This will allow you to keep making guesses until you get it right, and doesn't repeat any code. Although this doesn't limit you to only 3 guesses. To do that, we should introduce one more variable:
var youHaveWon = false;
var guessesRemaining = 3;
while( ! youHaveWon && guessesRemaining > 0 ) {
var random = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10... you have " + guessesRemaining + " more guesses");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
youHaveWon = true;
}
else {
alert("Sorry, the correct answer was " + random);
}
guessesRemaining = guessesRemaining - 1;
}
if ( ! youHaveWon ) {
alert("You lost");
}
You can wrap this to a function and return it on right value. Upon return, JS will stop execution and control will move forward
Try below
function findNumber() {
var random = Math.floor(Math.random() * 10);
var random1 = Math.floor(Math.random() * 10);
var random2 = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10, you have 3 chances.");
if (answer === random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return true;
} else {
alert("Sorry, the correct answer was " + random);
window.prompt("Make a guess from 1 to 10, you have 2 chances left.");
}
if (answer == random1) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return true;
} else {
alert("Sorry, the correct answer was " + random1);
window.prompt("Make a guess from 1 to 10, you have 1 chance left.");
}
if (answer == random2) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return true;
} else {
alert("Sorry, the correct answer was " + random2);
alert("You've lost");
}
}
The problem is that you're having three different if-blocks which all will be executed even though the user might have guessed the correct number yet.
I'd recommend setting up a single random number and a global counter which keeps track of the remaining chances.
function validate() {
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
if (chances - 1 > 0) {
chances--;
answer = window.prompt("Make a guess from 1 to 10, you have " + chances + " chances.");
validate();
}
}
}
var random = Math.floor(Math.random() * 10);
var chances = 3;
var answer = window.prompt("Make a guess from 1 to 10, you have " + chances + " chances.");
validate();
var randomNumbers = [];
var numberOfTries = 3;
for(var i=0; i<numberOfTries ; i++){
randomNumbers.push(Math.floor(Math.random() * 10));
}
for(var i=numberOfTries-1; i > -1 ; i--){
var answer = window.prompt("Make a guess from 1 to 10, you have "+ parseInt(i + 1) +" chances left.");
if(answer === randomNumbers[i]) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return;
}
else {
alert("Sorry, the correct answer was " + randomNumbers[i]);
}
}
In the following JavaScript code you answer both questions and then you will get a specific answer based on your score.
Let's say, you choose Yes a lot for the first question and Chocolate for the second question, you will score 8 points and instead of displaying the number 8 I would like to display a comment. That's why I have created an if loop, but for some reason the javascript code is displaying nothing, any suggestions for a solutions?
By the way you can find the code in the following link:
http://jsfiddle.net/9N5ZV/
if (totalScore <=2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Your condition syntax is wrong, and you use variables out of scope.
Demo
function getTotal()
{
var totalScore = getScoreCake() + getScoreChoco();
document.getElementById('result').innerHTML =
//"Your total score is: "+totalScore;
getComment(totalScore);
}
function getComment(score)
{
if (score <=2)
return healthy;
else if(score >= 3 && score <=6)
return average;
else
return unhealthy;
}
You need an else if
if (totalScore <=2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Also, use the console! You'll see:
Uncaught SyntaxError: Unexpected number
This was due to the else (expr) clause, it's else if
You conditional statement has errors. Should be:
if (totalScore <= 2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Here is an updated jsFiddle.
EDIT:
You are not calling getComment function. Try the one below to see how you can output the string.
http://jsfiddle.net/9N5ZV/5/
This question already has answers here:
Prime Number Determination Javascript
(1 answer)
finding sum of prime numbers under 250
(9 answers)
How to find prime numbers between 0 - 100?
(40 answers)
Closed 9 years ago.
I have a really small knowledge of JS
And I was wondering that if someone inputted a number, if they could tell it was prime.
function prime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0 && i !== num) {
break;
} else {
console.log("true")
}
}
}
My sister gave me this challenge, and I don't know how to do this... Any hints or tips, or a code I could dissect and understand how it works?
Thanks,
Find sqrt of your number after that loop number from i = 2 to sqrt(your_number) if your_number % === 0 this is end - this number is not a prime number.
Short example with number 37.
var n = 37;
var m = Math.sqrt(n);
var isPrime = true;
for (var i = 2; i <= m; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
document.write(n + ' - Prime number<br/>');
} else {
document.write(n + ' Is not prime number<br/>');
}
This question already has answers here:
Testing whether a value is odd or even
(23 answers)
Closed 9 years ago.
Can anyone point me to some code to determine if a number in JavaScript is even or odd?
I'm trying to do something like:
if(intellect is even)
{
var magic1 = intellect/2;
}
else
{
var magic1 = (intellect-1)/2
}
var magicdamage = Math.floor(Math.random) * (intellect + weaponi) + magic1
Use the modulus operator
if(intellect % 2 == 0)
{
alert ('is even');
}
else
{
alert('is odd');
}
I think the most robust isEven function is:
function isEven(n) {
return n == parseFloat(n) && !(n % 2);
}
which leads to:
function isOdd(n) {
return n == parseFloat(n) && !!(n % 2);
}
See Testing whether a value is odd or even
if( var % 2 == 0){ /*even*/} else {/*odd*/}
Works for Java, Javascript and any other language. It's a very simple solution, that's why it often doesn't come into your mind until you've seen it somewhere.
The modulo operator % will return the remainder of a division. If the number being divided is even, the remainder is 0.
Like this:
var i = 2;
if (i%2)
// i is odd
else
// i is even
Try using this:
var number = 3;
if (number % 2)
{
//it is odd
}
else
{
//it is even
}