only final output is being displayed - javascript

I'm trying to make a program to roll three random dice with n number of sides (determined by user input), and then continue rolling the dice and showing the random numbers until all three numbers are the same.
I think my logic is fine, but the page only shows the final row where all the numbers are the same and not the ones prior to it (where they are not all the same).
{
let sidesNumber = parseInt(prompt("Enter the number of sides for your dice:", ""));
let output1 = -1;
let output2 = -2;
let output3 = -3;
while( output1 != output2 || output1 != output3 )
{
output1 = Math.floor((Math.random()* sidesNumber + 1));
output2 = Math.floor((Math.random()* sidesNumber + 1));
output3 = Math.floor((Math.random()* sidesNumber + 1));
document.getElementById("result").innerHTML = output1 + " " + output2 + " " + output3;
}
}

The reason this is happening is you are not appending output1, output2, and output3 the Math.floor((Math.random()* sidesNumber + 1)), you are redefining the whole variable.
For example,
let output1 = -1;
let output2 = -2;
let output3 = -3;
output1 = Math.floor((Math.random()* sidesNumber + 1));
output2 = Math.floor((Math.random()* sidesNumber + 1));
output3 = Math.floor((Math.random()* sidesNumber + 1));
The output varaible is -1, -2, etc.
So to append the variables as Math.floor((Math.random()* sidesNumber + 1)), use += instead of =.
I've also realized document.getElementById("result").innerHTML = should be document.getElementById("result").innerHTML +=. I fixed that too.
{
let sidesNumber = parseInt(prompt("Enter the number of sides for your dice:", ""));
let output1 = -1;
let output2 = -2;
let output3 = -3;
while( output1 != output2 || output1 != output3 )
{
output1 += Math.floor((Math.random()* sidesNumber + 1));
output2 += Math.floor((Math.random()* sidesNumber + 1));
output3 += Math.floor((Math.random()* sidesNumber + 1));
document.getElementById("result").innerHTML += output1 + " " + output2 + " " + output3;
}
}

You're very almost there.
Currently, instead of displaying each roll on the screen, your script rolls the dice invisibly in the background and the roll is displayed only when the desired result occurs.
To display each roll, swap the line:
document.getElementById("result").innerHTML = output1 + " " + output2 + " " + output3;
for something like:
document.body.innerHTML += '<p>' + output1 + " " + output2 + " " + output3 + '</p>';
Working Example:
{
let sidesNumber = parseInt(prompt("Enter the number of sides for your dice:", ""));
let output1 = -1;
let output2 = -2;
let output3 = -3;
while( output1 != output2 || output1 != output3 )
{
output1 = Math.floor((Math.random()* sidesNumber + 1));
output2 = Math.floor((Math.random()* sidesNumber + 1));
output3 = Math.floor((Math.random()* sidesNumber + 1));
document.body.innerHTML += '<p>' + output1 + " " + output2 + " " + output3 + '</p>';
}
}

Here is a working example storing the values inside a ul element
{
let sidesNumber = parseInt(prompt("Enter the number of sides for your dice:", ""));
let output1 = -1;
let output2 = -2;
let output3 = -3;
while( output1 != output2 || output1 != output3 )
{
output1 = Math.floor((Math.random()* sidesNumber + 1));
output2 = Math.floor((Math.random()* sidesNumber + 1));
output3 = Math.floor((Math.random()* sidesNumber + 1));
document.getElementById("result").innerHTML += "<li>" + output1 + " " + output2 + " " + output3 + "</li>";
}
}
<ul id="result"></ul>

Note that every time you run your code you override the value of the innerHTML with =, you just have to fix it by writing +=
document.getElementById("result").innerHTML += output1 + " " + output2 + " " + output3;

Related

turning a for loop into while loop

what is the best way to convert this into a while loop?
<html>
<head>
<script type="text/javascript">
<!--
function GetGrades() {
var grades = [];
var grade;
var sum = 0;
for(i=0; i<5; i++) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
}
for(i=0; i<5; i++) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
}
var avg = sum/5.0;
document.write("</br>Grade: " + avg + "</br>");
}
//-->
</script>
</head>
<body onload="GetGrades()">
</body>
</html>
I have ignorantly tried to simply declare the variable i as sero and change the for to while.
while(i<5) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
i++;
}
while(i<5) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
i++;
}

Calculating average from array and recieving a NaN error

I'm having issues with trying to convert objects from a string array into integers. I've used parseInt and parseFloat but none of it is working. Do I need to maybe structure the array declaration differently or the prompt?
Thanks guys
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=1; i<=10; i++){
scores[i] = prompt("Enter score " + i);
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(sum + scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
You're using the for loop for prompt from 1 to 10, but calculating the sum in Average looping 0 to 9. The scores[0] is undefined as it is never assigned a value in the prompt loop whcih results to NaN when added to other numbers. Also you're adding sum in parseInt which is wrong.
Here is the fixed code :
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores[i] = prompt("Enter score " + (i+1));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Hope this helps !
following line is wrong in your code :
scores[i] = prompt("Enter score " + i);
I have written a small piece of javascript code which will do the average calculation. What it's doing is, getting the number in a variable from the prompt and pushing it into the array.
function calAverage(){
var sum = 0;
for (var i = 0; i < scores.length; i++){
sum += scores[i];
}
var avg = sum/scores.length;
return avg;
}
var scores = [];
for (var i=1; i<=10; i++){
var number = prompt("Enter score :");
scores.push(parseInt(number));
}
console.log(scores);
var average = calAverage(scores);
console.log("Average = " + average);
There are a few issues here:
scores[i] = prompt("Enter score " + i);, I would exchange this for scores.push(parseInt(prompt("Enter score " + i)));, as prompt returns a string, upon which most operations will fail and return NaN. Setting scores[i] = does work, but can be messy if you try to scale it up.
sum += parseInt(sum + scores[i]);, you have already got the +=, and as such the extra sum + ... effectively translates to sum = (2 * sum) + scores[i], meaning we can reduce this to sum += scores[i];
The complete code:
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores.push(parseInt(prompt("Enter score " + i)));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += scores[i];
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Here's the working code:
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<=9; i++){
scores[i] = prompt("Enter score " + (i+1));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + (i + 1) + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i], 10);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Thanks for the help, Andreas.
I did some modification in your code and also applied a check if user enter any value other than a number.
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores[i] = parseFloat(prompt("Enter score " + (i+1)));
if(isNaN(scores[i])){
scores[i]=0;
}
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
Average();
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
<div id="average"></div>

Javascript User-input for operators not outputing the integers

I'm supposed to take a few numbers and give them out in a list prompt.
EDIT, SOLVED thank you
concatenate the variables with the operators like you did with "Num 1= " + num1 , and you can do the math directly in the document.write without reassigning result each time :
var entry;
var average;
var total = 0;
entry = prompt("enter first number");
entry = parseInt(entry);
var num1 = entry;
total = total + num1;
entry = prompt("enter second number");
entry = parseInt(entry);
var num2 = entry;
total = total + num2;
average = parseInt(total / 2);
document.write("<h2>Arithmetic and operators</h2>")
document.write('Num 1 = ' + num1 + ' <br> Num 2 = ' + num2 + ' <br> Average num = ' + average + '<br>')
document.write(num1 + ' + ' + num2 + ' = ' + ( num1 + num2 ));
document.write("<br>")
document.write(num1 + ' - ' + num2 + ' = ' + ( num1 - num2 ));
document.write("<br>")
document.write(num1 + ' / ' + num2 + ' = ' + ( num1 / num2 ));
document.write("<br>")
document.write(num1 + ' % ' + num2 + ' = ' + ( num1 % num2 ));
document.write("<br>")
document.write(num1 + ' * ' + num2 + ' = ' + ( num1 * num2 ));
document.write("<br>")

User enters 2 numbers, output numbers and sums in table. Outputting, but not in table?

Write a program that asks a user to enter three numbers. If all three entries are numbers then output the sum of all combinations of pairs of numbers from the three entries. The code that performs the addition and outputs the result for each pair should be in a function and is called from the main function. Output the answers in an HTML table. The table and its end tag should be added to the HTML page. The table rows will be inserted with the program.
I can get the program to mostly work, but it's not outputting the numbers and sums as part of the table, and I'm not sure where/what I'm missing?
//function to output sum of number1 and number2
function outputSumOfnumber1Andnumber2(number1, number2) {
var output;
sum1and2 = number1 + number2;
output = document.getElementById('outputPart2');
output.innerHTML += "<tr><td>" + number1 + "</td><td>" + number2 + "</td><td>" + sum1and2 + "</td></tr>";
}
function outputSumofnumber2Andnumber3(number2, number3) {
var output;
sum2and3 = number2 + number3;
output = document.getElementById('outputPart2');
output.innerHTML += "<tr><td>" + number2 + "</td><td>" + number3 + "</td><td>" + sum2and3 + "</td></tr>";
}
function outputSumofnumber1Andnumber3(number1, number3) {
var output;
sum1and3 = number1 + number3;
output = document.getElementById('outputPart2');
output.innerHTML += "<tr><td>" + number1 + "</td><td>" + number3 + "</td><td>" + sum1and3 + "</td></tr></table>";
}
function exercise3Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
var number1;
var number2;
var number3;
var output;
var tableRows;
number1 = Number(prompt("Enter a number:"));
number2 = Number(prompt("Enter another number:"));
number3 = Number(prompt("Enter one more number:"));
output = document.getElementById('outputPart2');
output.innerHTML = "<table><tr><th>Pair part 1</th><th>Pair part 2</th><th>Sum</th></tr>";
outputSumOfnumber1Andnumber2(number1, number2);
outputSumofnumber2Andnumber3(number2, number3);
outputSumofnumber1Andnumber3(number1, number3);
}
Attempt 2--
//function to output sum of numbers
function outputSumOfnumbers(number1, number2, number3, rows) {
var output;
var rows;
sum1and2 = number1 + number2;
sum2and3 = number2 + number3;
sum1and3 = number1 + number3;
output = document.getElementById('outputPart2');
rows = "<tr><td>" + number1 + "</td><td>" + number2 + "</td><td>" + sum1and2 + "</td></tr>";
rows += "<tr><td>" + number2 + "</td><td>" + number3 + "</td><td>" + sum2and3 + "</td></tr>";
rows += "<tr><td>" + number1 + "</td><td>" + number3 + "</td><td>" + sum1and3 + "</td></tr>";
}
function exercise3Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
var number1;
var number2;
var number3;
var myTable;
var rows;
myTable = document.getElementById('outputPart2');
number1 = Number(prompt("Enter a number:"));
number2 = Number(prompt("Enter another number:"));
number3 = Number(prompt("Enter one more number:"));
outputSumOfnumbers(number1, number2, number3);
myTable = document.getElementById('outputPart2');
myTable.innerHTML += rows;
}
Well, you messed things up, but instead of fixing this code, I prefer that you choose a better approach on table manipulation, this is definitely NOT the way you should do it.
Check this article: http://www.htmlgoodies.com/beyond/css/working_w_tables_using_jquery.html
I believe that you will get it right when you apply what is inside. (:
I added an opening and closing table tag to my HTML (with an id) and used the below code:
//function to output sum of number1 and number2
function outputSumOfnumber1Andnumber2(number1, number2) {
var output;
sum1and2 = number1 + number2;
output = document.getElementById('outputPart2');
output.innerHTML += "<tr><td>" + number1 + "</td><td>" + number2 + "</td><td>" + sum1and2 + "</td></tr>";
}
function outputSumofnumber2Andnumber3(number2, number3) {
var output;
sum2and3 = number2 + number3;
output = document.getElementById('outputPart2');
output.innerHTML += "<tr><td>" + number2 + "</td><td>" + number3 + "</td><td>" + sum2and3 + "</td></tr>";
}
function outputSumofnumber1Andnumber3(number1, number3) {
var output;
sum1and3 = number1 + number3;
output = document.getElementById('outputPart2');
output.innerHTML += "<tr><td>" + number1 + "</td><td>" + number3 + "</td><td>" + sum1and3 + "</td></tr></table>";
}
function exercise3Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
var number1;
var number2;
var number3;
var output;
var tableRows;
number1 = Number(prompt("Enter a number:"));
number2 = Number(prompt("Enter another number:"));
number3 = Number(prompt("Enter one more number:"));
output = document.getElementById('outputPart2');
output.innerHTML = "<tr><th>Pair part 1</th><th>Pair part 2</th><th>Sum</th></tr>";
outputSumOfnumber1Andnumber2(number1, number2);
outputSumofnumber2Andnumber3(number2, number3);
outputSumofnumber1Andnumber3(number1, number3);
}

Why is the output being overwritten for this javascript

Expanded a previous question and it is working fine with the exception to the daily output. As the user enters each week/daily intake of supplement packs it should display to screen until the number of days entered is met. If a user input 2 weeks and 3 days (number of days packs were taken each week) the output should look like:
Week 1
Number of packs taken on Day 1 = 2
Number of packs taken on Day 2 = 1
Number of packs taken on Day 3 = 3
Week 2
Number of packs taken on Day 1 = 1 etc....
My code keeps writing over Week 1. I'm sure this is something simple that I overlooked. Maybe a variable to hold each weeks input? My code thus far...thanks for the help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Daily Supplement Intake Log</title>
<script>
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
while(i < numWeeks) {
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
while(d < daysPerWeek){
var packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
subtotal is " + sum + " supplement packs." + "<br>"
+ "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
}
document.getElementById("output4").innerHTML="The total for these weeks
is " + grandTotal + " supplement packs." + "<br>";
}
</script>
<body>
<header><h1>Daily Supplement Packet Log</h1></header><br>
<section>
<div class="align">
<label>Number of weeks:</label>
<input type="text" name="textbox" id="week" value=""><br>
<label>Number of days per week:</label>
<input type="text" name="textbox" id="day" value=""><br></div>
<div id="button">
<button type="button" id="log" onclick="getSup()">Enter number of packs
taken each day</button></div>
</section>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
<div id="output4"></div>
</body>
</html>
Using document.createElement method to dynamically create and order output divs. JSFiddle demo.
First replace your <div id="output1"></div>, ...2, ...3, and ...4 divs with:
<div id="outputs"></div>
<div id="total"></div>
...and then swap your getSup function with this:
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
var packsTaken;
var tempDiv, weekListText
var outputs = document.getElementById("outputs");
while(i < numWeeks) {
d = 0;
grandTotal = 0;
maxPacks = 0;
highDay = 0;
weekListText = '';
while(d < daysPerWeek){
packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
//document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
weekListText += "Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
//document.getElementById("output1").innerHTML="Week " + i + "<br />";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i;
outputs.appendChild(tempDiv);
// formerly known as output2
tempDiv = document.createElement('div');
tempDiv.innerHTML = weekListText;
outputs.appendChild(tempDiv);
//document.getElementById("output3").innerHTML="Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
outputs.appendChild(tempDiv);
}
document.getElementById("total").innerHTML="The total for these weeks is " + grandTotal + " supplement packs." + "<br>";
}
This is mostly the same as the original, but I've rem'ed out the old innerHTML assignments and moved the vars up to the top of the function to reflect actual variable scope.
You overwrite the html, you do not append to it like you do in the loop.
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
should be
document.getElementById("output1").innerHTML += "Week " + i + "<br />";
document.getElementById("output3").innerHTML += "Week " + i + ";
but that is not going to make the output you want since they are the same sections. You really should be appending new elements to the page.
var header = document.createElement("h2");
header.innerHTML = "Week " + i;
document.getElementById("output1").appendChild(header);
var div = document.createElement("div");
div.innerHTML = "new content";
document.getElementById("output1").appendChild(div);

Categories