Please help with simple javascript program

ibex333

Diamond Member
Mar 26, 2005
4,094
123
106
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.
 
Last edited:

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
You have a fundamental misunderstanding of how to use parseFloat (or any other function that returns a value). Take another look at it.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
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.
 

ibex333

Diamond Member
Mar 26, 2005
4,094
123
106
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.
 
Last edited:

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
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?
 

ibex333

Diamond Member
Mar 26, 2005
4,094
123
106
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!
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
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. :)
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
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.
 
Last edited:

Danimal1209

Senior member
Nov 9, 2011
355
0
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!
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
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
 

beginner99

Diamond Member
Jun 2, 2009
5,320
1,768
136
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

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.
 

ibex333

Diamond Member
Mar 26, 2005
4,094
123
106
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?
 
Last edited:

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
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).

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.
 
Last edited:

beginner99

Diamond Member
Jun 2, 2009
5,320
1,768
136
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.
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
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.
 
Last edited:

ibex333

Diamond Member
Mar 26, 2005
4,094
123
106
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?
 

tatteredpotato

Diamond Member
Jul 23, 2006
3,934
0
76
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
}
 

ibex333

Diamond Member
Mar 26, 2005
4,094
123
106
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.

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

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

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
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.
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
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.
 
Last edited: