Writing a Number Guessing program in JavaScript - javascript

Here is the question im trying to address and here is what I have. I am not sure what i've done wrong but it will not run in WebStorm:
alert("This is question 1");
var rndmNum = Math.rndmNum();
rndmNum = rndmNum * 100 + 1;
var i = 0;
do {
var rndmNum = prompt;
function guessNum(guess) {
if (guess < rndmNum);
}
alert("Your guess is too low");
} else if (guess > rndmNum) {
alert("Your guess is too high");
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Question 1</title>
</head>
<body>
<h1>Question 1</h1>
<p>
This is a page used to run/execute some JavaScript.
</p>
<p>
Next question.
</p>
<p>
Return home.
</p>
</body>
</html>
does anyone see any problems in what I have done or have any recommendations? Feedback is appreciated thanks

There's a syntax error:
function guessNum(guess) {
if (guess<rndmNum);
}
alert ("Your guess is too low");
}
else if (guess>rndmNum) {
alert("Your guess is too high");
}
Should be:
function guessNum(guess) {
if (guess<rndmNum) {
alert ("Your guess is too low");
}
else if (guess>rndmNum) {
alert("Your guess is too high");
}
}
You have an else if when your if statement was separated by an alert.
Also
Your brackets {} do not properly close.
The do is not syntactically correct or needed.
Math.rndmNum() is not a real method, think you want Math.random()

I only briefly looked at it. I don't really approve of giving answers for homework questions, but I will pose a question for you.
What if someone puts in something besides a number? You check if the answer is lower or higher, but you never make sure that it's actually a number.
You might want to consider either validating that the answer being checked is a number before checking it, or checking only for the answer you're looking for.
Also, var i = 0. I'll assume that you're going to use that later in your code, but i is pretty much a universal JavaScript variable.
What you're doing there is setting the global variable i to = 0, and most likely you're going to change that somewhere else in your code. Then you might run a for loop that rewrites i, or you might have an extension that rewrites it.
Consider naming your variables more uniquely, or keep the scope of the variables that aren't unique to functions or loops.

first of all. if you want to generate random number use:
Math.random() because Math.rndmNum is undefined
prompt is function and to use it you should write:
var rndmNum = prompt('geuss a number');
to convert random number from float to integer:
rndmNum = Math.floor(rndmNum * 100 +1);
and do-while loop should be:
do {
var rndmNum = prompt('geuss a number');;
function guessNum(guess) {
if (guess<rndmNum){
alert ("Your guess is too low");
}else if (guess>rndmNum) {
alert("Your guess is too high");
}
}
i++;
}while(i<10) // number of guesses

Related

If statements with emojis

I'm just starting javascript so I apologize if anything I say is unclear. I'm trying to write a function that see's if the var emoji is the same as a specified emoji. I have an else statement following it - as a fall through. ```
function match1() {
var emoji = document.getElementById("emoji");
if (emoji == "&#128516"){
document.getElementById("demo").innerHTML = "correct";
}
else {
document.getElementById("demo").innerHTML = "not correct";
document.getElementById("emoji").innerHTML = "&#128542";
}
}
Everything run's fine, except the if statement never actually happens, even when emoji does equal &#128516. Is that if statement something that will never work or have I just written it wrong?
Your problem is that, when you get the emoji, it's not the HTML escape chars, but the actual rendered HTML, as you can see:
console.log(document.getElementById("emoji").innerHTML);
<p id="emoji">&#128516</p>
Anyways, to compare an emoji, just do it like you always do in an if statement, but use the rendered version of the emoji in the JavaScript, not the escape chars. Also, as someone pointed out in the comments, document.getElementById("emoji") will return something like <p id="emoji">😂</p>, not just the content. You can get the content with innerHTML or innerText.
Here's a working example of your question:
function match1() {
var emoji = document.getElementById('emoji').innerHTML;
if (emoji === "😄") {
document.getElementById("demo").innerHTML = "correct";
} else {
document.getElementById("demo").innerHTML = "not correct";
document.getElementById("emoji").innerHTML = "&#128542";
}
}
match1();
<p id="emoji">&#128516</p>
<p id="demo"></p>

Get this Troll Program working

Scenario :
Attempted to create this troll 'guessing game program'.
It prompts the user to guess a number between 1-10, and the user will
get it wrong each time until they guess all numbers, frustrated, I
tell them to guess one last time, upon this attempt, it says your
answer was right!
Code - I am new at JS so I have not really gone into DOM manipulation and the code for some reason does not work.
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<script type="text/javascript">
var numset = 0;
var guess = numset + 1;
var max = numset >= 11;
while (guess !== max) {
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
} else {
alert("You Won! Number of guesses: 11")
}
</script>
</body>
</html>
Todo :
Please correct this
or Suggest any better approach, i am open to options.
Thank You.
One option would be to use a Set of numbers between 1 and 10, prompt for a number and remove it from the set until the set is empty, and then display the total number of guesses.
Note that because the program uses prompt, it will block the user's browser - consider using something less user-unfriendly, like an input and a button / enter listener, if at all possible.
// Set of numbers from 1 to 10:
const numSet = new Set(Array.from(
{ length: 10 },
(_, i) => i + 1
));
let guesses = 1; // to account for the final guess at the end
while(numSet.size > 0) {
const guessed = prompt("I am guessing a number between 1-10, let's see if you can guess it!");
numSet.delete(Number(guessed));
guesses++;
}
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
alert("You Won! Number of guesses: " + guesses)

If user's answer is NaN, alert NaN and ask again for a number

I'm writing a function that asks a user for a number and returns the sqrt of that number. If they don't provide a number I need to alert(NaN) and prompt for a number again. Not sure what I'm doing wrong here, it is returning the sqrt but I can't get the NaN part to work.
function sqrtUserNum() {
let userNum = parseFloat(prompt("Give me a number and I'll tell you it's square-root."));
if (isNaN(userNum)) {
alert(NaN)
prompt(userNum)
}
if (!isNaN(userNum)); {
alert(Math.sqrt(userNum))
}
}
sqrtUserNum()
The problem is how you're prompting again with this prompt(userNum)
First, extract the prompt part.
I recommend you to use do-while-loop for looping and ask for a number when is not a number.
Use the object Number instead to avoid problems with strings like this 4yryr
function askFor() {
return Number(prompt("Give me a number and I'll tell you it's square-root."));
}
function sqrtUserNum() {
let userNum;
do {
userNum = askFor();
if (isNaN(userNum)) {
alert(NaN);
} else {
alert(Math.sqrt(userNum))
}
} while (isNaN(userNum));
}
sqrtUserNum();
As comments have pointed out, you have typos in the code. What you probably are trying to achieve is something like:
function sqrtUserNum() {
let userNum;
for (;;) {
userNum = parseFloat(prompt("Give me a number and I'll tell you it's square-root."));
if (!isNaN(userNum))
break;
alert("The number was not valid!");
}
alert(Math.sqrt(userNum));
}
sqrtUserNum()
In other words, you want to alert the user that the number was invalid and try again, until you get an actual number.
Programming is a good bit about following grammar rules, and the following is 'dubious':
if (!isNaN(userNum)); {
alert(Math.sqrt(userNum))
}
This is because the extra ; causes it to be parsed as:
if (!isNaN(userNum)) /* do nothing */;
/* block unrelated to conditional, which is always executed */
{
alert(Math.sqrt(userNum))
}
See the Block Statement
At first, you had some typos in your code.
If you want to keep requesting a number if the user does not enter one, I modified your script to do exactly that. (I can't really tell from your question):
function sqrtUserNum() {
let userNum = parseFloat(prompt("Give me a number and I'll tell you it's square-root."));
while (isNaN(userNum)) {
alert("NaN");
userNum = parseFloat(prompt("Please enter a number."));
}
alert(Math.sqrt(userNum));
}
sqrtUserNum();
In case you do not want to do that, this should do it:
function sqrtUserNum() {
let userNum = parseFloat(prompt("Give me a number and I'll tell you it's square-root."));
if (isNaN(userNum)) {
alert("NaN");
userNum = parseFloat(prompt("Give me a number and I'll tell you it's square-root."));
}
if (!isNaN(userNum)) {
alert(Math.sqrt(userNum));
}
}
sqrtUserNum();

check for alpha only colors using javascript

I am trying to check for alpha only charachters only on a webpage using javascript
Javascript
function AlphaOnly(x,fieldname) {
var valueToCheck=x.value;
var letters = /^[A-Za-z]+$/;
if(valueToCheck.length == 0) {
alert("Please Enter a " + fieldname);
x.focus();
return false;
}
else if(valuetoCheck.match(/[\W_]/)){
alert("Alpha only");
}
else if(letters.test(valuetocheck)) {
alert("its working");
}
}
It works if the field is empty but cant get it to work if its not alpha charachters entered
Also want to change the color of an element
function ChangeColor(x) {
x.style.backgroundColor="red";
}
I didnt put in the html as the functions are being called, they just wont do what they are suppose to.
Any help would be appreciated
Thanks
Rachael
The valueToCheck variable is not keeping consistent case, and that appears to be causing the problem here, because javascript's variable names are case-sensitive.
This fiddle shows a working example with nothing changed but the variable name fixed: http://jsfiddle.net/jt3RC/

javascript as a virus?.... source Edited

Heres my simple html source
<html>
<head>
<title>
Dec2Bin
</title>
<script type="text/javascript">
function app() {
var decimal = prompt("Numero en Decimal");
alert("El numero " + decimal + " en codigo binario es igual a " + dec2bin(decimal));
}
function dec2bin(decimal) {
var binario = "";
while (decimal != 0) {
if (decimal % 2 == 0) {
binario += "1";
}
else {
binario += "0"
}
decimal = decimal / 2
}
return binario;
}
</script>
</head>
<body>
<input type="button" onclick="app()" value="Procesar" />
</body>
</html>
Avg keeps telling me its a virus.. if I remove the javascript it stops... what can I do?
You appear to have an endless loop because decimal will never equal 0. I could see where AVG might not like this.
function dec2bin(decimal) {
var binario="";
while(decimal!=0) {
if(decimal % 2==0)
binario+="1";
else
binario+="0"
}
decimal/=2
return binario ;
}
I did a quick google search and pulled up a cleaner function:
function dec2bin(dec) {
var bits = [];
var remainder = 0;
while (dec >= 2) {
remainder = dec % 2;
bits.push(remainder);
dec = (dec - remainder) / 2;
}
bits.push(dec);
bits.reverse();
return bits.join("");
}
I'm not 100% sure if this is the cause, but your while-loop:
while(decimal!=0)
{
if(decimal % 2==0)
binario+="1";
else
binario+="0"
}
doesn't terminate because decimal doesn't change until outside the loop. Thus, running that loop should lock up your browser.
The only other thing I can see in your updated code is that your prompt does not coerce decimal to a number.
If the user doesn't input a number, decimal/2 will return NaN, which will never equal zero, so your loop won't terminate. I would suggest using parseInt to convert to an integer, and then if that returns NaN, you could either assign 0 to decimal or find some other way to skip your while-loop (such as changing your while-loop's condition to decimal != 0 || decimal != NaN.
I doubt that an anti-virus would pick that up, but it's not impossible.
Whilst it would be lovely if AV tools could automatically solve the halting problem(!), it is likely just another in a long string of false positives from today's utterly hopeless anti-virus industry. Maybe renaming some variables and moving the code about a bit would stop it in the short term, but in general false positives are a tiresome fact of life for any programmer.
The only other thing to check is: is AVG detecting that exact source posted above in a local file with nothing else in it as a virus? For me, AVG at virustotal is not flagging such a file as suspicious. Does it only detect it online? If so you would need to inspect the View->Source to see that there hasn't been a compromise on your server unexpectedly injecting a malicious script into the page at serve-time.
Best thing to do is uninstall AVG. Virus scanners are a scam, and they significantly reduce the performance of your machine. If you're really worried about malware, best thing to do is install ubuntu as the main OS of your machine and run windows inside a VM such as virtual box.

Categories

Resources