Reputation: 1
I got bored and decided to make a script, but it isn't working. Instead of adding the numbers, it treats them as strings, ex. 0 + 42 + 0 + 17 would be 042017. Also, the while script goes on forever.
var money = 0;
var yn = false;
var bye = 0;
var add = window.prompt("How many dollars do you want?");
console.log("You got " + add + " dollars!");
parseFloat(add);
money += add;
add = 0;
console.log(money);
while (money < 1000000001 || bye == 1) {
yn = window.confirm("Do you want more money?");
if (yn) {
add = window.prompt("How many dollars do you want?");
console.log("You got " + add + " dollars!");
parseFloat(add);
money += add;
console.log(money);
} else {
console.log("Goodbye!");
bye = 1;
};
};
if (money > 999999999) {
console.log("You won the game with " + money + " dollars!");
};
Upvotes: 0
Views: 75
Reputation: 101680
Most likely the reason your while
loop is going on forever is because of the bye
variable. Your logic is broken.
If the user answers No to the prompt, bye
will be set to 1
and never change back. The while
loop will continue as long as bye
is 1, so it will go on forever.
To fix this, you can use:
while (money < 1000000001 && bye !== 1) {
or
while (money < 1000000001 || bye === 0) {
However, to store an on/off flag, you should be using a boolean variable, not a number:
var bye = false;
// ....
while (money < 1000000001 && !bye) {
// ....
if (yn) {
// ....
} else {
// ....
bye = true;
}
}
Also note that you don't need (read: shouldn't use) a semicolon after if
and while
blocks.
Upvotes: 0
Reputation: 239473
When you do
parseFloat(add);
it converts add
to a floating point value and returns it. Since you are ignoring it, add
remains unchanged as a string. You might want to replace the new value in add
, like this
add = parseFloat(add);
Also, you can just convert the result of window.prompt
itself, like this
add = parseFloat(window.prompt(...));
Upvotes: 2