Please help with simple javascript program

Discussion in 'Programming' started by ibex333, Sep 9, 2012.

  1. ibex333

    ibex333 Diamond Member

    Joined:
    Mar 26, 2005
    Messages:
    3,430
    Likes Received:
    0
    Reusing this thread to ask another question. Please look at my most recent post


    Code:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
    	<script type="text/javascript">
    	//	declare variables
    	var firstName;
    	var lastName;
    	var fullName;
    	var openingBalance;
    	var firstDeposit;
    	var secondDeposit;
    	var thirdDeposit;
    	var totalAccBal_1;
    	
    	//declare constants
    	var BR = "<br />";
    	
    	
    	
    	//user input
    	firstName = prompt("Please enter your first name.");
    	lastName = prompt("Please enter your last name.");
    	fullName = firstName + " " + lastName;
    	openingBalance = prompt("Enter your opening balance.");
    	firstDeposit = prompt("Enter your first deposit.");
    	secondDeposit = prompt("Enter your second deposit.");
    	thirdDeposit = prompt("Enter your third deposit.");
    	
    	//perform conversions	
    	parseFloat(openingBalance);
    	parseFloat(firstDeposit);	
    	parseFloat(secondDeposit);
    	parseFloat(thirdDeposit);
    	parseFloat(totalAccBal_1);
    	
    	//perform calculations
    	totalAccBal_1 = openingBalance + firstDeposit + secondDeposit + thirdDeposit;
    	
    	
    	
    	
    	//display all information
    	document.write("The purpose of this program is to act as a banking simulation" + BR);
    	document.write("<====================================================================>" + BR);
    	document.write("Welcome" + " " + " " + fullName + BR)
    	document.write("Your opening balance is: " + " " + openingBalance + " " + BR);
    	document.write("Your first deposit is: " + " " + firstDeposit + " ");
    	document.write("Your second deposit is: " + " " + secondDeposit + " ");
    	document.write("Your third deposit is: " + " " + thirdDeposit + " " + BR);	
    	document.write("Your account balance after the 3 deposits is: " + totalAccBal_1 + BR);
    	
    	//end the program
    	document.write("Good-Bye, " + fullName + "!");
    	</script>
    </body>
    </html>
    

    When I try to get a total account balance after the 3 deposits the program concatenates instead of adding and I fail to see why. I already spent 4 hours trying to figure this out myself, and I cannot take it anymore. I need some help, as much as I'd love to be able to do this solo.
     
    #1 ibex333, Sep 9, 2012
    Last edited: Sep 26, 2012
  2. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,682
    Likes Received:
    3
    You have a fundamental misunderstanding of how to use parseFloat (or any other function that returns a value). Take another look at it.
     
  3. KLin

    KLin Lifer

    Joined:
    Feb 29, 2000
    Messages:
    29,312
    Likes Received:
    0
    Very important. :D
     
  4. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,682
    Likes Received:
    3
    Another hint... suppose I have a function that adds two numbers and returns the resulting value, and I call it as follows...

    Code:
    function add(a, b) {
        return a + b;
    }
    
    var a = 1;
    var b = 2;
    
    add(a, b);
    
    alert(a);
    
    What will be the value reported for 'a' in the alert dialog? When you figure this out look back at your code, and you'll see the issue.
     
  5. ibex333

    ibex333 Diamond Member

    Joined:
    Mar 26, 2005
    Messages:
    3,430
    Likes Received:
    0
    Markbnj, I dont know what alert does and how to use it.


    Edit: nvm. I know how to use it now, but still cant see whats wrong with my code.
     
    #6 ibex333, Sep 10, 2012
    Last edited: Sep 10, 2012
  6. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,682
    Likes Received:
    3
    I honestly feel like we've laid it out there almost in black and white for you. If this isn't homework I'll just give you the answer. But if it is homework, meaning you're supposed to be learning to program, then I feel like you need to think this through.

    One more hint: if a function returns a value, and nobody saves that value, assigns that value, or does anything with that value at all... did the function really run?
     
  7. ibex333

    ibex333 Diamond Member

    Joined:
    Mar 26, 2005
    Messages:
    3,430
    Likes Received:
    0
    YES!

    I finally got it by flipping though the chapter in the book. Basically what I was doing is converting my input to a float, but NOT storing the value anywhere! And the reason why this happened is because I had no idea what the proper syntax is when using parseInt and parseFloat.

    This is my homework, so thank you for not just giving me the answer. I didn't want that.

    I suppose I have to apologize for being so dumb. I am a hardware tech for a living, and because this stuff doesn't pay, I decided to take up programming in college. I find it extremely hard, because my mind just refuses to think in such ways, but I am forcing it to, because I really want to do this. I've gotten in the habit to work with my hands, not with my brain, so time to break that habit!
     
  8. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,682
    Likes Received:
    3
    No, you don't have to apologize at all. You went through exactly the right process. You'll remember how this works now. Congrats on your perseverance. :)
     
  9. Cerb

    Cerb Elite Member

    Joined:
    Aug 26, 2000
    Messages:
    17,409
    Likes Received:
    0
    No one's brain naturally thinks in those ways. Programming is applied mathematics, and it is hard. Anyone without many years of experience* that thinks it isn't is either a genius, or someone I don't want to have to rely on for good code. It becomes easier with training and practice, to the point that much of it reaches the level of intuition, but that comes from years of creating and expanding related neural pathways.

    * That is, the kind of person that forgot what it was like to not understand the basics.
     
    #10 Cerb, Sep 11, 2012
    Last edited: Sep 11, 2012
  10. Danimal1209

    Danimal1209 Senior member

    Joined:
    Nov 9, 2011
    Messages:
    355
    Likes Received:
    0
    It has taken me an intro to programming class and 3 java classes to get a decent grasp of the language. It isn't something you can learn in a few days. You just need to keep at it and you'll start to get a good hold of it. Good luck!
     
  11. EagleKeeper

    EagleKeeper Discussion Club Moderator<br>Elite Member
    Staff Member

    Joined:
    Oct 30, 2000
    Messages:
    42,600
    Likes Received:
    0
    If one has a calculator, it more than likely uses the new math. One learns to think like that.

    TI and their cheap calculators. :thumbsdown:

    Vs the old HP RPN that says take two variables, operate on them and store the answer somewhere. :thumbsup: That is the way computers actually work
     
  12. beginner99

    beginner99 Platinum Member

    Joined:
    Jun 2, 2009
    Messages:
    2,810
    Likes Received:
    2
    Do you need to know how a car works to drive it?

    Personally I always felt Programming very intuitive. But sometimes you just need to look at the documentation. i sometimes have exactly the same issue as OP if I don't now whether the method returns a new value or changes it.
     
  13. ibex333

    ibex333 Diamond Member

    Joined:
    Mar 26, 2005
    Messages:
    3,430
    Likes Received:
    0
    Ok.. so now I am a little further into the class and I got a new assignment, and yet again I am stuck. I been sitting here for hours, making sure my code is "correct" and it seems that way, but clearly there is a mistake! I just cannot find it and I need some help. As you can see this is only a small part of the program I need to write, but I am trying to slowly work through it one piece at a time until I finish it. The issue is somewhere in the "else if" statement for the withdrawal, unless I am wrong.

    Code:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
    	<script type="text/javascript">
    	//	declare variables
    	var firstName; 
    	var lastName;
    	var fullName;
    	var openingBalance; //this is the initial balance
    	var userInput; //this will store whatever was the input
    	var depositAmount; //deposit you made
    	var withdrawalAmount; //withdrawal you made
    	var ES = " "; //empty space
    	var BR = "<br />"; //break
    	
    	
    	
    	//ask the user to fill in vital info
    firstName = prompt("Please enter your first name");
    lastName = prompt("Please enter your last name");
    fullName = (firstName + ES + lastName);
    openingBalance = prompt("Please enter your opening balance");
    	
    	
    	//Ask the user to choose an action to perform
    userInput = prompt("Hello," + fullName + "." +  ES + "Please enter 'D' for Deposit, 'W' for Withdrawal or 'B' to check your balance");
    	
    	//This code if for deposit
    	if (userInput === "D") {
    depositAmount = prompt("Enter the amount of your deposit");
    
    	}
    	else if (depositAmount < 0) {
    alert("Amount less than zero! Enter amount again!");
    	}
    
    openingBalance = parseFloat(openingBalance);
    depositAmount = parseFloat(depositAmount);
    openingBalance = (openingBalance + depositAmount);
    openingBalance = parseFloat(openingBalance);
    document.write("With the deposit, your balance is now" + ES + openingBalance + BR);
    
    	//This code is for withdrawal
    	
    	if (userInput === "W") {
    withdrawalAmount = prompt("Enter the amount of your withdrawal");
    
    	}
    	else if (withdrawalAmount < 0) {
    alert("Amount less than zero! Enter amount again!");
    	}
    	
    openingBalance = parseFloat(openingBalance);
    withdrawalAmount = parseFloat(withdrawalAmount);
    	
    	else if (openingBalance >= withdrawalAmount) {
    	openingBalance = (openingBalance - withdrawalAmount);
    	}
    openingBalance = parseFloat(openingBalance);
    document.write("After the withdrawal, your balance is now" + ES + openingBalance + BR);
    }	
    	else {
    	alert("Your balance is less than your withdrawal amount!");
    	}
    
    
    
    	
    	//end the program
    document.write("Good-Bye, " + fullName + "!");
    	</script>
    </body>
    </html>
    
    Also, can someone please teach me some ways to catch bugs when writing Javascript code? When I took a Java intro course, netbeans would point out bugs in a very subtle way. I couldnt understand 90% of it, but rarely I would get at least a vague idea about what was my mistake from the cryptic messages. With Javascript though I dont see any way to help myself find my mistakes. The program simply wont run and my browser remains blank. I can sit there forever looking at the blank screen, then at my code in notepad++, and I still dont know what the hell I did wrong.

    My professor showed in class how to catch bugs using the alert(), but I didn't understand what that was all about and now he doesn't want to explain it again.

    Please dont suggest stuff like Visual Studio or Firebug. These things require learning how to use them, and I dont have time for that. I am trying to concentrate on learning Javascript. Are there any less involved ways of catching bugs?
     
    #14 ibex333, Sep 26, 2012
    Last edited: Sep 26, 2012
  14. Cerb

    Cerb Elite Member

    Joined:
    Aug 26, 2000
    Messages:
    17,409
    Likes Received:
    0
    This here at the top is not directly related to the code not working. It's more, "I hate seeing code like this, so please don't become another programmer that does it." :p

    However, it is indirectly related, as you'll see by another problem with the code.

    Initialize variables ASAP, and once, within each highest scope possible (in this code, just once for each).

    Code:
    openingBalance = prompt("Please enter your opening balance");
    ...
    openingBalance = parseFloat(openingBalance);
    openingBalance = (openingBalance + depositAmount);
    openingBalance = parseFloat(openingBalance);
    ...
    openingBalance = parseFloat(openingBalance);
    Here's what the code taking the initial variables aught to look something like:
    Code:
    firstName = prompt("Please enter your first name");
    lastName = prompt("Please enter your last name");
    fullName = (firstName + ES + lastName);
    openingBalance = prompt("Please enter your opening balance");
    openingBalance = parseFloat(openingBalance);
    
    Doing that, you don't need to worry about calling parseFloat anywhere else, for that variable. It gets taken care of very close to the input code itself (prompt()).

    You can probably wrap them together, but that's more of a style thing:
    Code:
    openingBalance = parseFloat( prompt( "Please enter your opening balance") );
    I haven't done much JS in awhile, so if that doesn't work...():)

    Right after you take the input, turn it into the relevant number format (which, for any real use, should be integer or fixed-point). OK, now that's not why it isn't working, but that can help clean your code up, and help in the long run, make it easier to read, easier to spot problems, and easier to catch exceptions that occur later on in the program.

    OK, now on to the functional problem(s). As you'll see, the functional problems and style problems are not unrelated.

    Look at this:
    Code:
    [b]if[/b] [COLOR="Green"]([/COLOR]userInput [COLOR="DarkOrange"]===[/COLOR] "D"[COLOR="Green"])[/COLOR] [COLOR="Blue"]{[/COLOR]
        depositAmount [COLOR="DarkOrange"]=[/COLOR] prompt[COLOR="Green"]([/COLOR]"Enter the amount of your deposit"[COLOR="Green"])[/COLOR];
    [COLOR="Blue"]}[/COLOR]
    [b]else if[/b] [COLOR="Green"]([/COLOR]depositAmount [COLOR="DarkOrange"]<[/COLOR] 0[COLOR="Green"])[/COLOR] [COLOR="Blue"]{[/COLOR]
        alert[COLOR="Green"]([/COLOR]"Amount less than zero! Enter amount again!"[COLOR="Green"])[/COLOR];
    [COLOR="Blue"]}[/color]
    
    ...lines that shouldn't be out here on their own...
    See anything wrong? Notice how it stands right out, with good indentation (also, the above should help show why syntax highlighting text editors are the way to go)? White space is not enforced in most languages, because the width of a tab was never sufficiently standardized. That doesn't mean it is not exceptionally important.

    The top level should be something like:
    Code:
    if (userInput === "D") {
        1. Get input value.
        2. Convert and verify value.
        3. Do stuff with value.
        4. Respond/return stuff.
    }
    else if (userInput === "W") {
        1. Get input value.
        2. Convert and verify value.
        3. Do stuff with value.
        4. Respond/return stuff.
    }
    else if (userInput === "B") {
        Respond/return current balance only.
    }
    [B]else {
        Bad input. Handle it here.
    }[/B]
    The deposit value code goes inside the block for which userInput === "D" is true, not in parallel after it. You did the same with withdrawal and balance. Also, the bolded is missing. When correctness may be at stake, always follow out all logical paths. Even if a user shouldn't be able to enter an invalid value, you still want to make sure it is within the set of valid inputs. Not doing so can make for serious reliability and security problems.

    The full version of the quoted and colored code should instead look like:
    Code:
    [b]if[/b] [COLOR="Green"]([/COLOR]userInput [COLOR="DarkOrange"]===[/COLOR] "D"[COLOR="Green"])[/COLOR] [COLOR="Blue"]{[/COLOR]
        depositAmount [COLOR="DarkOrange"]=[/COLOR] prompt[COLOR="Green"]([/COLOR]"Enter the amount of your deposit"[COLOR="Green"])[/COLOR];
        depositAmount [COLOR="DarkOrange"]=[/COLOR] parseFloat[COLOR="Green"]([/COLOR]depositAmount[COLOR="Green"])[/COLOR];
    
        [b]if[/b] [COLOR="Green"]([/COLOR]depositAmount [COLOR="DarkOrange"]<[/COLOR] 0[COLOR="Green"])[/COLOR] [COLOR="Blue"]{[/COLOR]
            alert[COLOR="Green"]([/COLOR]"Amount less than zero! Enter amount again!"[COLOR="Green"])[/COLOR];
        [COLOR="Blue"]}[/COLOR]
        [COLOR="Purple"]// why allow a $0.00 deposit?
        // oh, and how they going to enter it again, without a loop?[/COLOR]
    
        [COLOR="Purple"]// openingBalance should have been handled above this, already. Omitting it.
        // re-using openingBalance is bad practice.[/COLOR]
    
        var resultingBalance [COLOR="DarkOrange"]=[/COLOR] [COLOR="Green"]([/COLOR]openingBalance [COLOR="DarkOrange"]+[/COLOR] depositAmount[COLOR="Green"])[/COLOR];
        document.write[COLOR="Green"]([/COLOR]"With the deposit, your balance is now" [COLOR="DarkOrange"]+[/COLOR] ES [COLOR="DarkOrange"]+[/COLOR] resultingBalance [COLOR="DarkOrange"]+[/COLOR] BR[COLOR="Green"])[/COLOR];
    [COLOR="Blue"]}[/COLOR]
    
    You should also be able to implement the last two lines as something like this, removing the need for the assignment line in the first place:
    Code:
    document.write[COLOR="Green"]([/COLOR]"With the deposit, your balance is now" [COLOR="DarkOrange"]+[/COLOR] ES [COLOR="DarkOrange"]+[/COLOR] [COLOR="Green"]([/COLOR]openingBalance [COLOR="DarkOrange"]+[/COLOR] depositAmount[COLOR="Green"])[/COLOR] [COLOR="DarkOrange"]+[/COLOR] BR[COLOR="Green"])[/COLOR];
    Now, the million-dollar question: did you jot down nicely indented pseudo-code, or at all diagram input->processing->output paths? We humans are fallible, and evolved to work in the physical world. Do not underestimate the power of writing things down, rather than just jumping into code. Understand the design, and follow every possible predicate after a[n externally exposed] state change (often a small number of good ones, and then a catchall for bad inputs). You need to understand what the design should be doing, as a control and/or data flow network or graph.

    Note that if you want to handle bad inputs to the number values, you'll want to make a function that loops over the input routine, for your sanity, and apply it to every number to be given by the user, with the ability to return a good value, cancel the current action or whole program, or pop back up with a blank field if given an invalid input (parseFloat fails).

    See above. I was working on the reply before your edit, which I assume is when you added that, because I don't recall seeing it at first. Personally, I'd stop at a syntax-highlighting and block-aware text editor (IE, that can fold blocks, and detect unclosed blocks), for such basic Javascript.
     
    #15 Cerb, Sep 26, 2012
    Last edited: Sep 27, 2012
  15. beginner99

    beginner99 Platinum Member

    Joined:
    Jun 2, 2009
    Messages:
    2,810
    Likes Received:
    2
    Since you ruled out tools to help you with debugging I can only tell you about a method I would in general try to avoid but it is very easy and has no learning curve. Just add alerts at critical points displaying whatever information is relevant at that point.
    With that you can determine where the code fails and you see if certain variables have unexpected values. However this method is very crude and should rather be avoided.

    What is you previous experience with programming?

    Personally i believe JavaScript is not the best one to learn first due to the fact that it also is a functional language. Maybe I'm just too dumb but I just did not get that for a pretty long time and it kept confusing me.
     
  16. Cerb

    Cerb Elite Member

    Joined:
    Aug 26, 2000
    Messages:
    17,409
    Likes Received:
    0
    Javascript is a multiparadigm language (this is for the OP). It's a bit imperative, a bit OO, and a bit functional. An in-thread example of why that can make it harder to learn is right in the first post, where a function not able to return a value did not bring up an error or warning by a compiler nor interpreter. In a functional language, that kind of thing generally wouldn't even compile; while using side effects as the main purpose of a call, and having the return value be optional or non-existent, is a common imperative thing to do.

    A language that were just functional would be a bit easier, in that such things wouldn't be allowed to slide by and silently execute to no effect.
     
    #17 Cerb, Sep 27, 2012
    Last edited: Sep 27, 2012
  17. DannyBoy

    DannyBoy Diamond Member

    Joined:
    Nov 27, 2002
    Messages:
    8,813
    Likes Received:
    0
  18. ibex333

    ibex333 Diamond Member

    Joined:
    Mar 26, 2005
    Messages:
    3,430
    Likes Received:
    0
    I have a new problem I cannot solve...

    So as I understand, "else if" will only fire if the previous condition was FALSE. But what if the previous condition was TRUE and I want to test the next condition RELATED to the previous one and execute it if it's TRUE?

    In plain English I am trying to say...

    If something was true, do this,

    But if something after that was true also, DO THAT TOO,

    and if something else after that was also true, DO THAT AS WELL.

    How do I write that in Javascript?
     
  19. ObscureCaucasian

    ObscureCaucasian Diamond Member

    Joined:
    Jul 23, 2006
    Messages:
    3,934
    Likes Received:
    0
    Code:
    if (condition1) {
      if (condition2) {
        // condition1 && condition2 are true
      }
    } else if (...) {
      // condition1 is not true
    }
    
     
  20. ibex333

    ibex333 Diamond Member

    Joined:
    Mar 26, 2005
    Messages:
    3,430
    Likes Received:
    0
    Obscure, thank you, but I am not sure if this is same as what I am trying to do.. Let me give you my code... I know it looks very long, but paste it into Notepad ++, it will be much easier to read.




    The following is the block of code I am having trouble with (even though it works)

     
  21. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,682
    Likes Received:
    3
    I think you need to back out of this a bit, because you're piling layers of highly dubious code one on top of the other. We can't really help you fix this because it's too bad. What you need is a hell of a lot simpler than what you've ended up with. You also have a number of syntactic issues that will simply break your logic, unless they are artifacts of copying/editing the code for posting.

    Some advice:

    Learn the precedence of operator execution. Especially boolean and logical operators. Learn how to correctly use parens to group logical statements together.

    Use variables for one reason and one reason only. I see places where you use a variable to collect input and then reuse it for a string value that is later used for output.

    From a high level: define an object that contains the boolean flags that will be set to true or false by the decision logic. Process that state object through all the user interrogation. Hand it off at the end to a method that displays the results.

    Modularize your code. Learn to recognize tasks and subtasks and represent each with a method.

    On your specific question: most programmers have an innate revulsion when confronted with deeply-nested 'if' statements, if only because a lot of us are slightly whacked and will do things like obsessively square the items on our desktops. There is, or should be, an in-bred aesthetic preference for spare, elegant code, and nested 'if' statements offend against both criteria.

    However, when you need to express the various steps in a decision tree sometime you don't have a choice. In that case you work to make them as tight and as elegant as possible.
     
  22. Cerb

    Cerb Elite Member

    Joined:
    Aug 26, 2000
    Messages:
    17,409
    Likes Received:
    0
    I like nested ifs right then and there for validation and exception handling that isn't duplicated. Beyond that, I start thinking about making a new function when I get to around 3.

    Also, please, please, use code tags! I'm not even going to try to read the large unindented blocks up there.
     
    #23 Cerb, Nov 11, 2012
    Last edited: Nov 11, 2012