Go Back   AnandTech Forums > Software > Programming

Forums
· Hardware and Technology
· CPUs and Overclocking
· Motherboards
· Video Cards and Graphics
· Memory and Storage
· Power Supplies
· Cases & Cooling
· SFF, Notebooks, Pre-Built/Barebones PCs
· Networking
· Peripherals
· General Hardware
· Highly Technical
· Computer Help
· Home Theater PCs
· Consumer Electronics
· Digital and Video Cameras
· Mobile Devices & Gadgets
· Audio/Video & Home Theater
· Software
· Software for Windows
· All Things Apple
· *nix Software
· Operating Systems
· Programming
· PC Gaming
· Console Gaming
· Distributed Computing
· Security
· Social
· Off Topic
· Politics and News
· Discussion Club
· Love and Relationships
· The Garage
· Health and Fitness
· Merchandise and Shopping
· For Sale/Trade
· Hot Deals with Free Stuff/Contests
· Black Friday 2014
· Forum Issues
· Technical Forum Issues
· Personal Forum Issues
· Suggestion Box
· Moderator Resources
· Moderator Discussions
   

Reply
 
Thread Tools
Old 09-09-2012, 08:22 PM   #1
ibex333
Diamond Member
 
ibex333's Avatar
 
Join Date: Mar 2005
Location: Ukraine, Odessa - New York City, Brooklyn ; )
Posts: 3,208
Default Please help with simple javascript program

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.
__________________
2500k Sandy Bridge @ 4.40GHz(Yay!)~GIGABYTE Z68A-D3H-B3~G.SKILL 8GB DDR3 1333~
3.14 Tb HD Space~EVGA GTX 670 FTW LE~HT Omega Claro~Cooler Master CM690~600w OCZ StealthXtream~ASUS 27" Monitor
HEATWARE
EBAY

Last edited by ibex333; 09-26-2012 at 08:09 PM.
ibex333 is offline   Reply With Quote
Old 09-09-2012, 08:35 PM   #2
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 12,543
Default

You have a fundamental misunderstanding of how to use parseFloat (or any other function that returns a value). Take another look at it.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is offline   Reply With Quote
Old 09-09-2012, 09:50 PM   #3
KLin
Lifer
 
KLin's Avatar
 
Join Date: Feb 2000
Location: Phreaznaux
Posts: 28,691
Default

Quote:
Originally Posted by Markbnj View Post
You have a fundamental misunderstanding of how to use parseFloat (or any other function that returns a value). Take another look at it.
Very important.
__________________
'L_'
KLin is offline   Reply With Quote
Old 09-09-2012, 11:04 PM   #4
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 12,543
Default

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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is offline   Reply With Quote
Old 09-10-2012, 02:22 AM   #5
ringtail
Senior Member
 
ringtail's Avatar
 
Join Date: Mar 2012
Location: USA left coast
Posts: 733
Default

This page may be helpful. It allows you to experiment with JavaScript programming. It produces results interactively
ringtail is offline   Reply With Quote
Old 09-10-2012, 10:18 AM   #6
ibex333
Diamond Member
 
ibex333's Avatar
 
Join Date: Mar 2005
Location: Ukraine, Odessa - New York City, Brooklyn ; )
Posts: 3,208
Default

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.
__________________
2500k Sandy Bridge @ 4.40GHz(Yay!)~GIGABYTE Z68A-D3H-B3~G.SKILL 8GB DDR3 1333~
3.14 Tb HD Space~EVGA GTX 670 FTW LE~HT Omega Claro~Cooler Master CM690~600w OCZ StealthXtream~ASUS 27" Monitor
HEATWARE
EBAY

Last edited by ibex333; 09-10-2012 at 10:35 AM.
ibex333 is offline   Reply With Quote
Old 09-10-2012, 11:37 AM   #7
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 12,543
Default

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?
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is offline   Reply With Quote
Old 09-10-2012, 11:46 AM   #8
ibex333
Diamond Member
 
ibex333's Avatar
 
Join Date: Mar 2005
Location: Ukraine, Odessa - New York City, Brooklyn ; )
Posts: 3,208
Default

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!
__________________
2500k Sandy Bridge @ 4.40GHz(Yay!)~GIGABYTE Z68A-D3H-B3~G.SKILL 8GB DDR3 1333~
3.14 Tb HD Space~EVGA GTX 670 FTW LE~HT Omega Claro~Cooler Master CM690~600w OCZ StealthXtream~ASUS 27" Monitor
HEATWARE
EBAY
ibex333 is offline   Reply With Quote
Old 09-10-2012, 12:11 PM   #9
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 12,543
Default

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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is offline   Reply With Quote
Old 09-11-2012, 12:39 AM   #10
Cerb
Elite Member
 
Cerb's Avatar
 
Join Date: Aug 2000
Posts: 15,366
Default

Quote:
Originally Posted by ibex333 View Post
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
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.
__________________
"The computer can't tell you the emotional story. It can give you the exact mathematical design, but what's missing is the eyebrows." - Frank Zappa

Last edited by Cerb; 09-11-2012 at 12:48 AM.
Cerb is offline   Reply With Quote
Old 09-24-2012, 12:07 AM   #11
Danimal1209
Senior Member
 
Join Date: Nov 2011
Posts: 345
Default

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!
Danimal1209 is offline   Reply With Quote
Old 09-24-2012, 08:15 AM   #12
EagleKeeper
Discussion Club Moderator
Elite Member
 
EagleKeeper's Avatar
 
Join Date: Oct 2000
Location: Bumps west of Denver
Posts: 42,600
Default

If one has a calculator, it more than likely uses the new math. One learns to think like that.

TI and their cheap calculators.

Vs the old HP RPN that says take two variables, operate on them and store the answer somewhere. That is the way computers actually work
__________________
F15 Air Superiority Fighter - Never has one been lost in aerial combat (104 kills)
EagleKeeper is offline   Reply With Quote
Old 09-25-2012, 02:08 AM   #13
beginner99
Platinum Member
 
Join Date: Jun 2009
Posts: 2,172
Default

Quote:
Originally Posted by EagleKeeper View Post
If one has a calculator, it more than likely uses the new math. One learns to think like that.

TI and their cheap calculators.

Vs the old HP RPN that says take two variables, operate on them and store the answer somewhere. That is the way computers actually work
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.
beginner99 is offline   Reply With Quote
Old 09-26-2012, 08:11 PM   #14
ibex333
Diamond Member
 
ibex333's Avatar
 
Join Date: Mar 2005
Location: Ukraine, Odessa - New York City, Brooklyn ; )
Posts: 3,208
Default

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?
__________________
2500k Sandy Bridge @ 4.40GHz(Yay!)~GIGABYTE Z68A-D3H-B3~G.SKILL 8GB DDR3 1333~
3.14 Tb HD Space~EVGA GTX 670 FTW LE~HT Omega Claro~Cooler Master CM690~600w OCZ StealthXtream~ASUS 27" Monitor
HEATWARE
EBAY

Last edited by ibex333; 09-26-2012 at 10:32 PM.
ibex333 is offline   Reply With Quote
Old 09-26-2012, 10:29 PM   #15
Cerb
Elite Member
 
Cerb's Avatar
 
Join Date: Aug 2000
Posts: 15,366
Default

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."

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:
if (userInput === "D") {
    depositAmount = prompt("Enter the amount of your deposit");
}
else if (depositAmount < 0) {
    alert("Amount less than zero! Enter amount again!");
}

...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.
}
else {
    Bad input. Handle it here.
}
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:
if (userInput === "D") {
    depositAmount = prompt("Enter the amount of your deposit");
    depositAmount = parseFloat(depositAmount);

    if (depositAmount < 0) {
        alert("Amount less than zero! Enter amount again!");
    }
    // why allow a $0.00 deposit?
    // oh, and how they going to enter it again, without a loop?

    // openingBalance should have been handled above this, already. Omitting it.
    // re-using openingBalance is bad practice.

    var resultingBalance = (openingBalance + depositAmount);
    document.write("With the deposit, your balance is now" + ES + resultingBalance + BR);
}
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("With the deposit, your balance is now" + ES + (openingBalance + depositAmount) + BR);
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).

Quote:
Are there any less involved ways of catching bugs?
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.
__________________
"The computer can't tell you the emotional story. It can give you the exact mathematical design, but what's missing is the eyebrows." - Frank Zappa

Last edited by Cerb; 09-27-2012 at 02:55 AM.
Cerb is offline   Reply With Quote
Old 09-27-2012, 12:41 AM   #16
beginner99
Platinum Member
 
Join Date: Jun 2009
Posts: 2,172
Default

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.
beginner99 is offline   Reply With Quote
Old 09-27-2012, 02:45 AM   #17
Cerb
Elite Member
 
Cerb's Avatar
 
Join Date: Aug 2000
Posts: 15,366
Default

Quote:
Originally Posted by beginner99 View Post
Personally i believe JavaScript is not the best one to learn first due to the fact that it also is a functional language.
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.
__________________
"The computer can't tell you the emotional story. It can give you the exact mathematical design, but what's missing is the eyebrows." - Frank Zappa

Last edited by Cerb; 09-27-2012 at 02:51 AM.
Cerb is offline   Reply With Quote
Old 11-05-2012, 08:51 AM   #18
DannyBoy
Diamond Member
 
DannyBoy's Avatar
 
Join Date: Nov 2002
Location: London, UK
Posts: 8,757
Default

Quote:
Originally Posted by ibex333 View Post
Also, can someone please teach me some ways to catch bugs when writing Javascript code?
Read up on try/catch - https://developer.mozilla.org/en-US/...ts/try...catch

Combine it with alerting your errors until you've learnt to use console tools like firebug etc.

Another link for you - http://www.javascriptkit.com/javatutors/trycatch.shtml
__________________
DannyBoy is offline   Reply With Quote
Old 11-10-2012, 10:24 PM   #19
ibex333
Diamond Member
 
ibex333's Avatar
 
Join Date: Mar 2005
Location: Ukraine, Odessa - New York City, Brooklyn ; )
Posts: 3,208
Default

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?
__________________
2500k Sandy Bridge @ 4.40GHz(Yay!)~GIGABYTE Z68A-D3H-B3~G.SKILL 8GB DDR3 1333~
3.14 Tb HD Space~EVGA GTX 670 FTW LE~HT Omega Claro~Cooler Master CM690~600w OCZ StealthXtream~ASUS 27" Monitor
HEATWARE
EBAY
ibex333 is offline   Reply With Quote
Old 11-10-2012, 10:38 PM   #20
ObscureCaucasian
Diamond Member
 
ObscureCaucasian's Avatar
 
Join Date: Jul 2006
Location: Raleigh, NC
Posts: 3,934
Default

Quote:
Originally Posted by ibex333 View Post
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?
Code:
if (condition1) {
  if (condition2) {
    // condition1 && condition2 are true
  }
} else if (...) {
  // condition1 is not true
}
ObscureCaucasian is offline   Reply With Quote
Old 11-10-2012, 11:23 PM   #21
ibex333
Diamond Member
 
ibex333's Avatar
 
Join Date: Mar 2005
Location: Ukraine, Odessa - New York City, Brooklyn ; )
Posts: 3,208
Default

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.

Quote:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
var natBornCitizen; // to ask if natural born citizen
var lawPermRes; // how many years have they been a lawful permanent resident.
var amtTerms; //amount of terms served as President.
var impeached; // if user ever been impeached by the U.S. Senate.
var rebel; // if ever rebelled against the U.S.
var ageOfUser; //ask the user their age.
var BR = "<br />"; // constant line break
var ES = " ";
var residency;
var cleanCriminalRecord;

// do you meet the citizenship test?





natBornCitizen = prompt("Are you a natural born citizen of the US? Enter Y/N");
natBornCitizen = natBornCitizen.toUpperCase();

while (!(natBornCitizen == 'Y' || natBornCitizen == 'y' || natBornCitizen == 'Yes' || natBornCitizen == 'yes' || natBornCitizen == 'N' || natBornCitizen == 'n' || natBornCitizen == 'No' || natBornCitizen == 'no'))

{
alert("You must only answer with Y, y, Yes, yes, N, n, No, or no");
natBornCitizen = prompt("Are you a natural born citizen of the US?");
natBornCitizen = natBornCitizen.toUpperCase();

}

/*if (natBornCitizen == 'Y' || 'N')
{
natBornCitizen = "you meet the citizenship requirement.";
}

else
{
natBornCitizen = " you do not meet the citizenship requirement.";
}
*/

// how many years user was a permanent resident
lawPermRes = prompt("How many years have you been a permanent resident of the U.S. as of today?");
lawPermRes = parseInt(lawPermRes, 10);
while (isNaN(lawPermRes) || lawPermRes < 0)
{
lawPermRes = prompt("You have entered an invalid response. How many years have you been a permanent resident of the U.S. as of today?", ES);
lawPermRes = parseInt(lawPermRes, 10);
}
/*if (lawPermRes >= 14)
{
document.write("You qualify." + BR);
}
else
{
document.write("You have not lived in United States long enough" + BR);
}
*/
//Amount of terms you served as president.
amtTerms = prompt("How many prior terms, if any, have you served as president?");
amtTerms = parseInt(amtTerms);
while (amtTerms < 0 || amtTerms > 2)
{
amtTerms = prompt("You have entered an invalid response. How many prior terms, if any, have you served as president?");
}

/*if (amtTerms <= 2)
{
document.write("You pass the served terms requirement." + BR);
}
else
{
document.write("You served too many terms and cannot be president.");
}
*/

// Was the user ever impeached.
impeached = prompt("Have you ever been impeached by the U.S. Senate? Please enter Y/N");
impeached = impeached.toUpperCase();
while (!(impeached === "Y" || impeached === "y" || impeached === "Yes" || impeached === "yes" || impeached === "N" || impeached === "n" || impeached === "No" || impeached === "no"))
{
impeached = prompt("You have entered an invalid response. You must only answer with Y or N");
impeached = impeached.toUpperCase();
}
/*if (impeached === "Y")
{
document.write("You fail to qualify." + BR);
}
else
{
document.write("This is good, you have never been impeached." + BR);
}
*/

// if user rebelled against the U.S. government.
rebel = prompt("Have you ever participated in a rebellion against the U.S.? Y/N");
rebel = rebel.toUpperCase();

while (!(rebel === "Y" || rebel === "y" || rebel === "Yes" || rebel === "yes" || rebel === "N" || rebel === "n" || rebel === "No" || rebel === "no"))
{
rebel = prompt("You have entered an invalid response. Please enter Y or N.");

}
/*if (rebel === "Y" )
{
document.write("You cant expect to be president if you rebelled against the US." + BR);
}
else
{
document.write("You never rebelled against the US and you pass that requirement." + BR);
}
*/
// Get user's age and see if they qualify.
ageOfUser = prompt("How old are you?");
ageOfUser = parseInt(ageOfUser);
while (ageOfUser <= 0)
{
ageOfUser = prompt("Age cant be zero or less! Enter your age again");
}


/*if (ageOfUser >= 35 || ageOfUser <= 100)
{
document.write("You meet the age criteria");

}
else (ageOfUser <= 35 || ageOfUser >= 100)
{
document.write("Unfortunately you do not meet acceptable age criteria for presidency.");
}
*/


//************************************************** ************************************************** ***********************

//TO PREPARE FOR CASES (probably could have somehow integrated this into the code above but not sure how that would work out becuase I'm combining two cases into one in some cases)
//alert("The status for impeached, is" + ES + impeached);
//alert("The status for rebel, is" + ES + rebel);

if (natBornCitizen = 'Y' && lawPermRes >= 14)
{
residency = true;
}
else
{
residency = false;
}
if (impeached === 'N' && rebel === 'N')
{
cleanCriminalRecord = true;
}
else
{
cleanCriminalRecord = false;
}

if (amtTerms >= 0 && amtTerms < 2)
{
amtTerms = true;
}
else
{
amtTerms = false;
}
if (ageOfUser >= 35 && ageOfUser <= 100)
{
ageOfUser = true;
}
else
{
ageOfUser = false;
}
//else
//{
//cleanCriminalRecord === false && residency === false && amtTerms === false && ageOfUser === false;
//}
alert("The status for residency, is" + ES + residency); //used to test, please ignore
alert("The status for cleanCriminalRecord, is" + ES + cleanCriminalRecord); //used to test, please ignore
alert("The status for amtTerms, is" + ES + amtTerms); //used to test, please ignore
alert("The status for ageOfUser, is" + ES + ageOfUser); //used to test, please ignore


//************************************************** ************************************************** ****************************

//And now the actual permutations with custom messages for each... I am not very good with math, but really, I cannot see how it's 16, even mathematically if we do 4!=4*3*2*1=24 ? 4n4=16 though, but each case doesnt exactly have 4 possible answers to it because of repetition?



//residency block
if (residency === true && cleanCriminalRecord === true && amtTerms === true && ageOfUser === true)
{
document.write("You meet all requirements for becoming president. Congratulations!");
}
else if (residency === true && cleanCriminalRecord === true && amtTerms === true && ageOfUser === false)
{
document.write("You meet the residency requirement, you have a clean criminal record, you did not serve more than one term as president, but you do not meet the age requirement for becoming president.");
}
else if (residency === true && cleanCriminalRecord === true && amtTerms === false && ageOfUser === false)
{
document.write("You meet the residency requirement, you have a clean criminal record, but you served more than one term as president, and you do not meet the age requirement for becoming president.");
}
else if (residency === true && cleanCriminalRecord === false && amtTerms === false && ageOfUser === false)
{
document.write("You meet the residency requirement, but you dont have a clean criminal record, you served more than one term as president, and you do not meet the age requirement for becoming president.");
}
//clean criminal record block
else if (cleanCriminalRecord === true && residency === false && amtTerms === false && ageOfUser === false)
{
document.write("You fail most presidency requirements, but you have a clean criminal record, which, although being a good thing, is not enough to make you a candidate for presidency");
}
else if (cleanCriminalRecord === true && residency === true && amtTerms === false && ageOfUser === false)
{
document.write("You meet the residency requirement, you have a clean criminal record, but you served more than one term as president, and you do not meet the age requirement for becoming president.");
}
else if (cleanCriminalRecord === true && residency === true && amtTerms === true && ageOfUser === false)
{
document.write("You meet the residency requirement, you have a clean criminal record, you did not serve more than one term as president, but you do not meet the age requirement for becoming president.");
}
else if (cleanCriminalRecord === true && residency === true && amtTerms === true && ageOfUser === true) //no real need for this, but adding it anyway to make 16 permutations
{
document.write("You meet all requirements for becoming president. Congratulations!");
}
// terms served block
else if (amtTerms === true && ageOfUser === false && cleanCriminalRecord === false && residency === false)
{
document.write("You didnt serve too many terms, which is good, but you do not meet any other criteria for becoming president ");
}
else if (amtTerms === true && ageOfUser === true && cleanCriminalRecord === false && residency === false)
{
document.write("You didnt serve too many terms, and you meet the age criteria, but you do not meet any other requirements for becoming president");
}
else if (amtTerms === true && ageOfUser === true && cleanCriminalRecord === true && residency === false)
{
document.write("You meet all requirements for becoming president except for residency requirement");
}
else if (amtTerms === true && ageOfUser === true && cleanCriminalRecord === true && residency === true) //no real need for this, but adding it anyway to make 16 permutations
{
document.write("You meet all requirements for becoming president. Congratulations!");
}
//users age block
else if (ageOfUser === true && amtTerms === false && cleanCriminalRecord === false && residency === false)
{
document.write("You do not meet any requirements to become president except your age which is within the accepted limits");
}
else if (ageOfUser === true && amtTerms === true && cleanCriminalRecord === false && residency === false)
{
document.write("You didn't serve too many terms, and you meet the age criteria, but you do not meet any other requirements for becoming president");
}
else if (ageOfUser === true && amtTerms === true && cleanCriminalRecord === true && residency === false)
{
document.write("You meet all requirements for becoming president except for residency requirement");
}
/*else if (ageOfUser = true && amtTerms = true cleanCriminalRecord = true && residency = true )
{
document.write("You meet all requirements for becoming president. Congratulations!"); //no need for this one
}
*/
else if (residency === false && cleanCriminalRecord === false && amtTerms === false && ageOfUser === false)
{
document.write("You fail every single criteria for becoming president, and you cannot ever become one.");
}




</script>
</body>

</html>



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

Quote:
if (natBornCitizen = 'Y' && lawPermRes >= 14)
{
residency = true;
}
else
{
residency = false;
}
if (impeached === 'N' && rebel === 'N')
{
cleanCriminalRecord = true;
}
else
{
cleanCriminalRecord = false;
}

if (amtTerms >= 0 && amtTerms < 2)
{
amtTerms = true;
}
else
{
amtTerms = false;
}
if (ageOfUser >= 35 && ageOfUser <= 100)
{
ageOfUser = true;
}
else
{
ageOfUser = false;
}
__________________
2500k Sandy Bridge @ 4.40GHz(Yay!)~GIGABYTE Z68A-D3H-B3~G.SKILL 8GB DDR3 1333~
3.14 Tb HD Space~EVGA GTX 670 FTW LE~HT Omega Claro~Cooler Master CM690~600w OCZ StealthXtream~ASUS 27" Monitor
HEATWARE
EBAY
ibex333 is offline   Reply With Quote
Old 11-11-2012, 11:42 AM   #22
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 12,543
Default

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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is offline   Reply With Quote
Old 11-11-2012, 03:12 PM   #23
Cerb
Elite Member
 
Cerb's Avatar
 
Join Date: Aug 2000
Posts: 15,366
Default

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.
__________________
"The computer can't tell you the emotional story. It can give you the exact mathematical design, but what's missing is the eyebrows." - Frank Zappa

Last edited by Cerb; 11-11-2012 at 04:21 PM.
Cerb is offline   Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -5. The time now is 05:31 AM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.