Javascript While Loop Returning Strange Results - javascript

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);

Related

How to fix infinite while loop and create functions

I am trying to make a paycheck program, that utilizes functions and while loops.
In this program, I have to create two functions, one for validating the pay rate and hours, and then one for the calculations.
In addition, I have to have the first function pass the hours and pay rate to the calculation function, and then pass it back to the first function. When I try to run the program with the first function, it seems that if I enter a pay amount under 7.25, it enters an infinite loop.
Here is the code
<script>
function payValidate(x)
{
if(isNaN(payRate) || payRate < 7.25 || payRate > 20)
{
return false;
}
else
{
return true;
}
}
function hoursValidate(x)
{
if(isNaN(hours) || hours < 1 || hours > 60)
{
return false;
}
else
{
return true;
}
}
var grossPay;
var withHolding;
var netPay;
var message;
var payRate = parseInt(prompt("Enter pay rate"));
var payRateOK = payValidate(payRate);
while(!payRateOK)
{
payRate = parseInt(prompt("Invalid pay rate. Enter pay rate again"));
payRateOk = payValidate(payRate);
}
var hours = parseFloat(prompt("Enter hours worked"));
var hoursOK = hoursValidate(hours);
while(!hoursOK)
{
hours = parseFloat(prompt("Invalid hours. Enter hours again"));
hoursOK = hoursValidate(hours);
}
grossPay = payRate * hours;
if(grossPay <= 300)
{
withHolding = grossPay * 0.10;
}
else
{
withHolding = grossPay * 0.12;
}
netPay = grossPay - withHolding;
var message = "Pay Rate: $" + payRate.toFixed(2) +
"\nHours Worked: " + hours +
"\nGross Pay $" + grossPay.toFixed(2) +
"\nWithholding $" + withHolding.toFixed(2) +
"\nNet Pay $" + netPay.toFixed(2);
alert(message);
</script>
You're creating a new variable payRateOk (notice the lower case k) instead of writing to payRateOK, the variable you check in the while loop. So payRateOK will never change, and the loop will execute infinitely.
var payRateOK = payValidate(payRate); // In here you have used "payRateOK"
while(!payRateOK)
{
payRate = parseInt(prompt("Invalid pay rate. Enter pay rate again"));
payRateOk = payValidate(payRate); // In here you have used "payRateok"
}
payRateOK != payRateOk there for you have to use same name for that
other thing is payRate is a float variable. you should use var payRate = parseFloat instead of var payRate = parseInt.
you have used hours as int type there for var hours = parseFloat should be var hours = parseInt

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

If statement in function issue

I can't get the if/else statement in the totalBalance function to work correctly in this code and I'm not sure why.
I have tried switching the greater than to less than and seeing if it solves the outcome but it makes no difference.
jsfiddle link
var moneyAmount = 0;
var food = 0;
var bills = 0;
var total = 0;
moneyAmount = prompt("how much money do you earn per month?");
amountCheck();
document.write("Your balance is " + "£" + moneyAmount + "<br>");
food = confirm("Do you have any food bills?");
if (food === true) {
food = prompt("How much per week?")
document.write("You spend £" + food + " on food per week <br>");
} else {
alert("Lucky!")
};
totalBalance();
/* total = moneyAmount - food; */
console.log("money amount = " + moneyAmount);
console.log("food = " + food);
console.log("total = " + total);
function totalBalance() {
total = moneyAmount - food;
console.log("total is " + total);
if (total > moneyAmount) {
document.write("Your total amount of money per month is £" + total);
console.log("nay");
} else {
document.write("You need to save more money £" + total);
console.log("yay");
};
}
function amountCheck() {
while (isNaN(moneyAmount)) {
alert("Please enter a numeric value");
moneyAmount = prompt("how much money do you have to spend?");
}
}
total will never be more than moneyAmount, because total is moneyAmount - food. So if (total > moneyAmount) will never evaluate as true unless food is a negative value. Not sure what exactly you're going for, but simply changing the if statement to if (total > 0) makes more sense to me given the context.

How to make computer guess a number and return number of guesses (Javascript)?

I'm currently working on a mini-project that I find interesting.
The basic idea is to have the user enter a number between 1 - 5, and have the computer guess that number, showing the number of guesses it took to guess it.
Here is my code so far ...
<html>
<head>
<title>Computer Guessing Game</title>
</head>
<body>
<p>How many fingers are you holding up?</p>
<input type = "text" id= "myNumber">
<button id="guess">Guess!</button>
<script type="text/javascript">
document.getElementById("guess").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var gotIt = false;
while (gotIt == false) {
var guess = Math.random();
guess = guess * 6;
guess = Math.floor(guess);
if (guess == myNumber) {
gotIt = true;
alert ("Got it! It was a " + guess + ". It took me " + /*number of guesses */ + " guesses.");
} else {
//computer should keep randomly guessing until it guessed correctly
}
}
}
</script>
</body>
As you can see, I can not figure out how to make the computer keep guessing the numbers and then print out to the user the number of guesses it took. I think that it's some sort of loop, but then again, I'm not sure.
Any help is appreciated (excuse me if I'm not writing the question clearly enough, I'm quite new to SO and will get better with time!).
I think you are pretty close to what you want. You can add a variable
var howManyGuesses = 0;
before the while loop, and increment this variable each time you calculate a new random number.
while(gotIt == false){
howManyGuesses = howManyGuesses + 1; //increment the amount of guesses
//your logic
alert ("Got it! It was a " + guess + ". It took me " + howManyGuesses + " guesses.");
}
To prevent it to loop forever you can do something like
var myNumber = document.getElementById("myNumber").value;
if (myNumber < 1 || myNumber > 5) {
alert('Please insert a number between 1 and 5');
return;
}

unescaped & or unknown entity "&&" 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).

Categories

Resources