...

View Full Version : Is a loop needed? I have NO idea !



samhor
03-19-2012, 11:17 PM
Hello All,

I have made the below code but i want to add something extra to it. I have tried to do it several times already but the code just seems to stop working :(

What i need it to do is to keep asking the user to enter the CD Title and CD Cost repeatedly and to total all the CD Costs together.


<html>
<body>
<script language='JavaScript'> //set the language
a=(prompt('please enter the CD Title:',0)); // enter the cd title promt
b=parseFloat(prompt('please enter the CD Cost:',0)); // enter the cd cost promt

document.writeln(' your CD Title is: <b>' + a + '</b>'); //write the cd title to the screen in bold
document.writeln(' your CD Cost is: <b>' + b + '</b>'); //write the cd cost to the screen


</script>
</body>
</html>


E.g.

Customer wants to buy X CD's.

The prompt will appear X times untill the customer has no more CD's they want to buy

All the CD Titles & CD Costs should be written to the screen

With Total

End Product:

your CD Title is: RnB Classic Vol 1 your CD Cost is: 1.00
your CD Title is: RnB Classic Vol 2 your CD Cost is: 1.00
your CD Title is: RnB Classic Vol 3 your CD Cost is: 1.00

Total Cost 3.00


Can anyone help?

webdev1958
03-19-2012, 11:22 PM
Since X can vary from user to user, I would use a WHILE loop to keep prompting the user for info and do any processing you need to do until a counter reaches X in value. Then output whatever data you need to display.

samhor
03-19-2012, 11:24 PM
Since X can vary from user to user, I would use a WHILE loop to keep prompting the user for info and do any processing you need to do until a counter reaches X in value. Then output whatever data you need to display.

Ummm I haven't got a clue on how to do while loops or loops in fact. My code just seems to stop working when i try.

webdev1958
03-19-2012, 11:28 PM
Ummm I haven't got a clue on how to do while loops or loops in fact. My code just seems to stop working when i try.

So what question are you asking then, and so I'm not sure what you want someone to do.

This sounds like a homework exercise. There is a good example/tutorial on WHILE loops on w3schools (http://www.w3schools.com/php/php_looping.asp)

Old Pedant
03-19-2012, 11:44 PM
I would suggest that, instead of first asking how many CDs the user wishes to buy, you instead simply keep asking the questions until the user responds with a blank answer (non-answer) to the first question.


My code just seems to stop working when i try.
And we won't write the code for you since this is homework. But if you SHOW us what you have tried, we might be able to give you clues as to what you are doing wrong.

Philip M
03-20-2012, 12:14 AM
I would suggest that, instead of first asking how many CDs the user wishes to buy, you instead simply keep asking the questions until the user responds with a blank answer (non-answer) to the first question.



Or clicks the cancel button (unlike a form field that returns null).
Hint - use a while loop .....

You have said "I haven't got a clue on how to do while loops or loops". If so, there is something seriously wrong. Have you not attended (or paid attention in) your classes, or is your teacher incompetent and sets assignments on topics not yet properly covered?

webdev1958
03-20-2012, 12:19 AM
Since X can vary from user to user, I would use a WHILE loop to keep prompting the user for info and do any processing you need to do until a counter reaches X in value. Then output whatever data you need to display.

Actually, I think a do-while loop is a better option. But in any case, depending on how you choose to do it, you could use a FOR, WHILE or DO-WHILE loop.

The w3schools link I posted has examples on all type of loops.

If you need more help, post back with your updated code :)

samhor
03-20-2012, 12:21 AM
I would suggest that, instead of first asking how many CDs the user wishes to buy, you instead simply keep asking the questions until the user responds with a blank answer (non-answer) to the first question.


And we won't write the code for you since this is homework. But if you SHOW us what you have tried, we might be able to give you clues as to what you are doing wrong.

Thanks for all your assumptions but you need correcting this is not homework put simply myself trying to upgrade my knowledge of js

Old Pedant
03-20-2012, 12:47 AM
Thanks for all your assumptions but you need correcting this is not homework put simply myself trying to upgrade my knowledge of js

Then, really, you shouldn't be using prompt() at all. Or document.write().

Learn to use <form>s and DOM methods, etc., as you really will need to do to create any normal web site.

webdev1958
03-20-2012, 12:50 AM
[0t]


you shouldn't be using prompt() at all. Or document.write().


There's nothing wrong with using prompt or document.write when starting out. Heck, even when I was at school we initially were taught how to use them. Not only to make us aware they exist but to help us learn the basics of looping without having to worry about the formatting or method of input/output too much.

Later on we moved onto more appropriate DOM methods :)



And we won't write the code for you since this is homework.

And who is the "we" you are referring to? I hope it's not me included in the "we" because you don't have the clout to speak on my behalf :). Although I don't normally do so, in the past, where appropriate I have written code for homework and I will continue to do so in the future where appropriate.

Also, I assume you are aware that doing someone's homework is not against this forums rules, but yes it is frowned upon.

[/ot]

Old Pedant
03-20-2012, 01:02 AM
I just don't think it is that much harder to learn to use a <form> than it is to learn to use promot( ) so I don't see the point in taking the time to learn to use the latter. But what the heck, you want to help him write this, then go for it!

And as for homework: I am citing the *SPIRIT* of Rule 1.5 of this forum. Yes, I know it doesn't specify that we can't give homework answers. It just says they can ask for homework answers. Semantic quibbling. The intent is clear, to me. Oh, and yes I have helped a *LOT* with homework. And on a few occasions tossed up my hands in frustration and written the code when I couldn't get across to the student. But I sure prefer to think that is a last resort. (On the other hand, I don't understand what relevance there is in, say, a Library Science student taking a course in JavaScript. It's really only those who claim to be computer science majors that bug me when they want us to write the code for them. Who the heck is going to do that for them when they get their first job?)

webdev1958
03-20-2012, 01:07 AM
That's ok :thumbsup: I was just making sure I wasn't included in your "we" :)

Old Pedant
03-20-2012, 01:09 AM
<html>
<body style="background-color: white;">
<script type-"text/javascript"> <!-- language= is obsolete -->
var total = 0;
while ( true )
{
a=(prompt('please enter the CD Title:','')); // enter the cd title promt
if ( a == "" ) break; // exit the loop when no title is given
b=parseFloat(prompt('please enter the CD Cost:',0)); // enter the cd cost promt
total += b;
document.writeln(' your CD Title is: <b>' + a + '</b><br/>'); //write the cd title to the screen in bold
document.writeln(' your CD Cost is: <b>$' + b.toFixed(2) + '</b><hr/>'); //write the cd cost to the screen
}
document.writeln(' your total cost for the CDs is: <b>$' + total.toFixed(2) + '</b>');
</script>
</body>
</html>


There. Homework or not, a solution that meets the request.

samhor
03-20-2012, 01:11 AM
I think i have done it now . Any ideas on how to put it in to a table to make it look nicer?

<html>
<pre>
<body>
<script language="JavaScript">

c=parseFloat(prompt("please enter the number of cds you will be purchasing:",0));
counter=0;
sum=0;

while (counter<c)

{


a=(prompt("please enter the CD Title:",0));
b=parseFloat (prompt("please enter the CD Cost:",0));

counter=counter+1;

sum=sum+b;

document.write("CD title entered: <b><i> " + a + "</b></i></br>");
document.write("CD cost entered: <b><i> " + b + "</b></i></br>");

}



document.write("total cost is:", "=", sum);

</script>
</body>
</pre>
</html>

webdev1958
03-20-2012, 01:13 AM
..... But what the heck, you want to help him write this, then go for it!


If the OP (not you ;)) comes back with updated code, I will :)

webdev1958
03-20-2012, 01:23 AM
I think i have done it now . Any ideas on how to put it in to a table to make it look nicer?


ok, from here you could continue using document.write() to create the html for the table, but at this stage you might like to consider more appropriate DOM methods to create the table.

For example:


var myTable = document.createElement('table');To add a row to the table you could then do


var newRow = myTable.insertRow(-1);To add a cell to the row you could do


var newCell = newRow.insertCell(-1);and to add content to a cell you could do:


newCell.appendChild(document.createTextNode('some text goes here'));Then you need to append the table to an element. To use KISS for now, to append the table to the <body> you could


document.body.appendChild(myTable);You would create the table element outside your loop and the rows and cells inside the loop. I would do the above after the page has loaded in a window.onload (google it if you need more info) so that the <body> has been created and the table can be appended to it.


Some useful w3schools tutes on the above:

createElement() (http://www.w3schools.com/dom/met_document_createelement.asp)

insertRow (http://www.w3schools.com/jsref/met_table_insertrow.asp)

insertCell (http://www.w3schools.com/jsref/met_tablerow_insertcell.asp)

appendChild (http://www.w3schools.com/dom/met_element_appendchild.asp)

Old Pedant
03-20-2012, 01:26 AM
I think i have done it now . Any ideas on how to put it in to a table to make it look nicer?

Yes, looks right.

You can easily put it into a table, but some browsers may not display the table until all rows are complete. That's one reason to use DOM methods instead of document.write.

But if you don't care about that, then something like this:


<html>
<body style="background-color: white;">
<table border="1" cellpadding="5">
<tr>
<th>Title of CD</th>
<th>Cost</th>
</tr>
<script type-"text/javascript"> <!-- language= is obsolete -->
var total = 0;
while ( true )
{
a=(prompt('please enter the CD Title:','')); // enter the cd title promt
if ( a == "" ) break; // exit the loop when no title is given
b=parseFloat(prompt('please enter the CD Cost:',0)); // enter the cd cost promt
total += b;
document.writeln("<tr><td>" + a + "</td><td>$" + b.toFixed(2) + "</td></tr>");
}
document.writeln('<tr><td style="text-align: right;font-weight: bold;">TOTAL:</td><td>$'
+ total.toFixed(2) + "</td></tr>");
</script>
</table>
</body>
</html>


But see webdev's answer. Though if you are ready to use DOM methods like that, you should be ready to use a <form> instead of prompt(), as well, in my opinion.

webdev1958
03-20-2012, 02:18 AM
If you want to see one way it can be done without using document.write() then expanding on my previous post, you could do something like this.

I'm using the KISS principle as much as possible with minimal user input validation.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
<style type="text/css"></style>
<script type="text/javascript">
window.onload=function(){
var totPrice = 0, askForTitle = true, newRow, newCell, title=' ';
var outTable = document.createElement('table');
while(askForTitle && title != null){
var title = window.prompt('Enter CD Title','');
if(title == '' || title == null){ //no title entered, so exit loop
askForTitle = false;
continue;
}
var price = Number(window.prompt('Enter price for "'+title+'"',''));
while(isNaN(price) || price <= 0){ //check if price is > 0
var price = Number(window.prompt('Enter price for "'+title+'"',''));
}
totPrice += price;
//create a row with 2 cells for this CD
newRow = outTable.insertRow(-1);
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode(title));
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode(price));
}
//now add a row for the total price
newRow = outTable.insertRow(-1);
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode('Total Price: '));
newCell = newRow.insertCell(-1);
newCell.appendChild(document.createTextNode(totPrice));
//append the table to the <body>
document.body.appendChild(outTable);
}
</script>
</head>
<body>

</body>
</html>


I know many use break; to exit loops but at school we had it drummed into us that it was a lazy way of breaking out of loops and that "logic" should be used rather than "brute force". The only place we were allowed to use break; was in a switch block. In the above example, I use a boolean to exit the while loop, but use whichever method you prefer.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum