unescaped & or unknown entity "&&" javascript - javascript

This is part of my homework but i can't figure out what is wrong and any help would be appreciated
var InputNum = prompt("Please enter a number between 50 and 100:", "");
if (isNaN(InputNum)) {
if (InputNum.match(/one|two|three|four|five|six|seven|eight|nine|ten/)) {
alert("while this is a number, it's not really a number to me.");
} else {
alert(InputNum + " doesn't appear to be a number.");
}
} else if (InputNum >= 99 && InputNum <= 51); {
alert("theat number, " + inputNum + ", is not between 50 and 100.");
}
document.write("The user gave a number in the range! " + inputNum + "<br>");
on line 25 it comes up with the warning that the title states.

The character & in HTML is reserved for entities, such as and ". This error is complaining about & being misused; it is a sign you should write it as & (which is the correct entity for the & symbol), or you should put your script in a context where it is not interpreted as HTML (such as CDATA).

Related

Math.random returning same value when console logged javascript [duplicate]

This question already has answers here:
Why does generating a random number outside of a loop, causes it to be always the same?
(2 answers)
Closed 1 year ago.
here is my code
// import user input prompt
var inquirer = require('inquirer');
var emptyFamArray = [];
// ask the user how many relatives do they have
const getQuestions = () => {
inquirer.prompt([
{
name: "relatives_names",
type: 'input',
message: "Please input family first names seperated by a space. only 1-10 family members please!",
},
]).then((answers => {
// console.log(answers)
let test1 = JSON.stringify(answers.relatives_names).split(' ');
// console.log(test1);
let randomArrayName = test1[Math.floor(test1.length * Math.random())]
let randomArrayNameTwo = test1[Math.floor(test1.length * Math.random())]
console.log(randomArrayName)
if(test1.length > 10){
console.log('to many names please input 10 or less')
} else if (test1.length == 9){
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
}else if (test1.length == 5){
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
when it console logs it does randomise the names but it only returns the same value over and over
example
kylee Gets gerald for christmas pickings!
kylee Gets gerald for christmas pickings!
kylee Gets gerald for christmas pickings!
how would I fix this? im stuck and not entirly sure how to make the variables random everytime when logged
Thanks
When you are printing to the console the random selection have already happened and it happens only ones before you print out the names.
To make it select a random name each time , convert the selection to a function which you will call every time you want to print to console. For example:
var selectRandomName = function(names) {
return names[Math.floor(names.length * Math.random())]
}
console.log(selectRandomName(names) + " GETS " + selectRandomName(names) + " for Christmas pickings!");
Obviously this is oversimplified and you probably should also prevent selection of the same name twice and other similar cases, but this is out of the scope of current question. I assume this is some sort of exercise, as in real world application you should use some readily available matching libraries.

How to store results of an iteration in a variable

For educational reasons, I am working through a simple algorithm that randomly generates two numbers and then asks for the addition of generated numbers, tells you if you are right or wrong on response, and tracks results out of 100. I would like to include function that reports something like the following: "You have gotten 80/100 correct" But am held up with syntax, I think. I can't get my score variable to count up with correct answers.
Here is my code as it stands..
do{
var firstnum = Math.floor(Math.random()*10);
var secondnum = Math.floor(Math.random()*10);
var result = firstnum+secondnum;
var score=0;
var answer = prompt("what is "+firstnum + "+" + secondnum);
if(answer < result || answer > result){alert("Wrong! " + "The correct answer
is " + result)};
if(answer == result){alert("you are correct!"), score++};
alert("Awesome, You have gotten " + score + " correct so far!!!");}
while(score<100);
Just get me over the hump. I am hopeful that I can really get my head wrapped around more concepts if I can get through this little guy.
You reset score in every loop to zero. Move the declaration and initialization to top.
Some hints:
no need for semicolons after a block statement { /* code */ },
convertion of strinn to number with unary plus +
use a single if statement with else block for the opposite of the check.
// declare all variables at top
var firstnum,
secondnum,
result,
score = 0,
answer;
do {
firstnum = Math.floor(Math.random() * 10);
secondnum = Math.floor(Math.random() * 10);
result = firstnum + secondnum;
// covert input string to number with unary plus
answer = +prompt("what is " + firstnum + "+" + secondnum);
// ^
// just check the result and omit a second if clause,
// because it is just the opposite check
// take the more easy/shorter check first
if (answer === result ) {
alert("you are correct!");
score++;
} else {
alert("Wrong! " + "The correct answer is " + result)
}
alert("Awesome, You have gotten " + score + " correct so far!!!");
} while (score < 2) // take a small number for scoring check

Trouble generating a random number between 0 and 10

I'm working in a discord bot, specifically in a rate command, which is supposed to return:
"I would rate (thing to be rated) (random number)/10."
But it returns:
"I would rate (thing to be rated) [object Undefined]/10."
client.on('message', message => {
if(message.content.startsWith (prefix + "rate")) {
if(message.content.slice(prefix.length + 4) === ""){
message.channel.send("Give me something to rate");
}
else
message.channel.send("I would rate" + "**" +
message.content.slice(prefix.length + 4) + "**" + " " +
toString(Math.floor(Math.pow(Math.random, 10))) + "/10");
}
What can possibly be wrong?
You need to incorporate the following code (considering you want round integers returned):
Math.floor(Math.random()*11)
Ditch the Math.pow() method.
edit made from suggestion by #Geert-Jan

Converted Int returns NaN

Here is my code
var fifty = prompt("Enter amount ");
var twenty;
alert(twenty=parseInt(fifty/50) + " x " + "50 dollar bill");
alert(parseInt(twenty/20) + " x " + "20 dollar bill");
What I'm trying to count is dollar bills.
For example when I enter "120" it should return 2x 50 bills and 1x 20 dollar bill, I understand that returned value is String type so I'm converting them number, but on 20 dollar bills it returns "Nan x 20 dollar bils" I'm having trouble understanding why
Please stop using parseInt for separating integer part of float value, use it only to convert string into integer. When you are using parseInt float value is converted into string and than some integer number is parsed back, there can be situation when float number will be converted in string like 5.1234E-6 and parseInt will return 5 in this case. Use Math.floor() instead.
var sum = parseInt(prompt("Enter amount "));
var twenty = Math.floor(sum/50);
alert(twenty + " x " + "50 dollar bill");
alert(Math.floor((sum - (twenty*50))/20) + " x " + "20 dollar bill");
I've shuffled around your variable names to make it a bit clearer.
// I'll use the example of 120 to demonstrate
// The total amount, e.g. 120
var amount = prompt("Enter amount ");
// First, convert the inputted string into an int
var amountAsInt = parseInt(amount, 10);
// Then, divide by 50 (which equals 2.4), and then use
// Math.floor() to "chop off" the decimal part
var numberOfFifties = Math.floor(amountAsInt/50);
// Leaving us with numberOfFifties = 2
// We can now use 'modulus' to give the amount left.
// If you haven't come across modulus before, it gives
// the remainder after dividing by the given number (here: 50)
var amountLeft = amount % 50;
// Do the same with the amount left to find the number of 20s
var numberOfTwenties = Math.floor(amountLeft / 20);
if(numberOfFifties > 0){alert(numberOfFifties + " x " + "50 dollar bill(s)");}
if(numberOfTwenties > 0){alert(numberOfTwenties + " x " + "20 dollar bill(s)");}
JSFiddle here:
http://jsfiddle.net/7p57e3u1/3/
Reason for the NaN
You can see the reason why you were getting an NaN by looking at this JSFiddle.
http://jsfiddle.net/pto52oe5/
You are setting twenty to be equal to the whole string, hence it is "Not a Number" (NaN).
alert(twenty=parseInt(fifty/50) + " x " + "50 dollar bill");
Here, you appear to be assuming that
twenty=parseInt(fifty/50)
will be treated as a separate "part", but in actual fact, it uses the whole expression, setting twenty to be the whole string that is output in the alert():
twenty = parseInt(fifty / 50) + " x " + "50 dollar bill"
i.e. (for the example above)
twenty = "2 x 50 dollar bill"
A useful technique for debugging (and creating more understandable and therefore maintainable code) is to split things down into very simple steps, as I have in the example code above. This (arguably) is broken down too far, but use that as a first technique to break down a problem like this.
You have a problem in your logic.
Maybe something like that:
http://jsfiddle.net/2e7cs06v/
var total = prompt("Enter amount ");
var numOf50=parseInt(total/50);
var moneyLeft = total - (numOf50 * 50);
alert(numOf50 + " x " + "50 dollar bill");
alert(parseInt(moneyLeft/20) + " x " + "20 dollar bill");
Note that I'm not trying to fix the algorithm here, but just the input errors and type.
You should first parse fifty to an int, then only divide it by 50, since you want an int even after dividing by 50 you can let the initial parseInt.
Also, be aware that parseInt needs a radix (10 here), and it may still return NaN if a non parseable value is given.
var fifty = parseInt(prompt("Enter amount "), 10);
alert(twenty=parseInt(fifty/50, 10) + " x " + "50 dollar bill");
As an alternative, you could use the bitwise or (|) which acts almoste like parseInt(x, 10) except that when it would have returned NaN with parseInt, it would return 0 with the bitwise or operator.
Using |
var fifty = prompt("Enter amount ") | 0;
alert(twenty=((fifty/50)|0) + " x " + "50 dollar bill");
Use following :
var fifty = prompt("Enter amount ");
var twenty;
twenty=parseInt(fifty/50);
var rem = fifty - (twenty * 50);
alert(twenty + " x " + "50 dollar bill");
alert(parseInt(rem/20) + " x " + "20 dollar bill");
Hope it will help !!
Because you have parsing more string (+ " x " + "50 dollar bill") into parseInt() function. So parseInt function not able to pars "dollar bill" text value.
var fifty = prompt("Enter amount ");
var twenty = parseInt(fifty/50);
alert( twenty + " x " + "50 dollar bill");
alert(parseInt(twenty/20) + " x " + "20 dollar bill");

Javascript While Loop Returning Strange Results

I apologize in advance if there are several things wrong with my code; I'm still very new to this.
I made a simple little RNG betting game, which follows:
var funds = 100;
var betting = true;
function roll_dice() {
var player = Math.floor(Math.random() * 100);
var com = Math.floor(Math.random() * 100);
var bet = prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign.");
if (player === com) {
alert("tie.");
}
else if (bet > funds) {
alert("You don't have that much money. Please try again");
roll_dice();
}
else if (player > com) {
funds += bet;
alert("Your roll wins by " + (player - com) + " points. You get $" + bet + " and have a total of $" + funds + ".");
}
else {
funds -= bet;
alert("Computer's roll wins by " + (com - player) + " points. You lose $" + bet + " and have a total of $" + funds + ".");
}
}
while (betting) {
var play = prompt("Do you wish to bet? Yes or no?");
if (funds <= 0) {
alert("You have run out of money.");
betting = false;
}
else if (play === "yes") {
roll_dice();
}
else {
alert("Game over.");
betting = false;
}
}
The code deals with losing (i.e. subtraction) just fine, but can't seem to handle the addition part. If you bet, say, 50 and win, you'll wind up with 10050. Aside from never seeking out a job as a gambling software programmer, what should I do?
prompt returns a string. Adding a number to a string results in a string:
> "12" + 13
"1213"
While subtraction results in an integer, as only string concatenation is done with a plus sign:
> "12" - 13
-1
You need to convert your user's input into an integer:
var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10);

Categories

Resources