0

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!");
};
1
  • The variable 'add' is of type String because the window.prompt() method returns a String type value. Whatever you add to a string using + will be like appending a string to a string. [link] w3schools.com/jsref/met_win_prompt.asp Commented Oct 10, 2014 at 4:54

2 Answers 2

2

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(...));
Sign up to request clarification or add additional context in comments.

2 Comments

That helps, but I still need to figure out why the while script isn't working.
@LouisExley Could you please explain "the while script isn't working"?
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.