javascript counter not displaying least number of doubles - javascript

Im trying to get a counter to register the least number of rolls it took to get a double and then when they play the 'game' again if they got an even lower number of doubles it replaces the first answer with the newer one.
count=0, doubles=0, lowest=10000000;
function Roll()
// Assumes: die images are in http://dave-reed.com/book/Images
// Results: displays a randomly selected image of a 6-sided die
{
var roll1, roll2;
roll1 = RandomInt(1, 6);
roll2 = RandomInt(1, 6);
document.getElementById('die1').src =
"http://dave-reed.com/book/Images/die" + roll1 + ".gif";
document.getElementById('die2').src =
"http://dave-reed.com/book/Images/die" + roll2 + ".gif";
count += 1;
if (roll1==roll2) {
doubles += 1;
}
if (doubles==3) {
alert("You got three pairs of doubles!!! It only took you " +count+ " rolls to get it! Now, go directly to jail, do not pass go, and do not collect $200");
doubles=0;
count=0;
}
if (doubles==3 && lowest>count){
lowest=count
document.getElementById('lowestLine').innerHTML = count;
}
document.getElementById('countLine').innerHTML = count;
document.getElementById('doublesLine').innerHTML = doubles;
}

You set doubles to 0 once it becomes 3 and then you check if doubles equals 3 which is never true.
It looks like you should put
if (lowest > count) {
lowest = count
document.getElementById('lowestLine').innerHTML = count;
}
inside first doubles === 3 check, but before you setting globals to 0.
Like this:
if (doubles === 3) {
alert("You got three pairs of doubles!!! It only took you " +count+ " rolls to get it! Now, go directly to jail, do not pass go, and do not collect $200");
if (lowest > count){
lowest = count
document.getElementById('lowestLine').innerHTML = count;
}
doubles = 0;
count = 0;
}

Related

JS star rating system

var num_stars_løn = 0
var num_stars_team = 0
var num_stars_trivsel = 0
function add_rating(num_rating, section) {
if (section == "løn"){
num_stars_løn = num_rating;
document.getElementById("num_stars_løn").value = num_rating;
}
else if (section == "teambuilding"){
num_stars_team = num_rating;
document.getElementById("num_stars_team").value = num_rating;
}
else if (section == "trivsel") {
num_stars_trivsel = num_rating;
document.getElementById("num_stars_trivsel").value = num_rating;
}
for(var i = 1; i < num_rating + 1; i++) {
var section_id = section + " " + i
document.getElementById(section_id).innerHTML = "★"
}
if (num_rating < 5){
for(var i = 5; i > num_rating; i--) {
var section_id = section + " " + i
document.getElementById(section_id).innerHTML = "☆"
}
}
if (num_stars_team > 0 && num_stars_løn > 0 && num_stars_trivsel > 0){
show_mean_rating();
}
}
function show_mean_rating() {
var mean = document.getElementById("num_stars_løn").value +
document.getElementById("num_stars_team").value +
document.getElementById("num_stars_trivsel").value;
document.getElementById("mean_rating").innerText = "Gennemsnitlig rating: " + (mean/3).toFixed(2);
}
HTML
I have made a star rating system for some topics (3 in total) using JavaScript and HTML. Do one of you know how to calculate the average/mean of how many stars each topic received? So not the three topics all together, but the mean per topic of clicks/stars.
Right now it finds the mean of all 15 stars in total. (each topic has 5 stars) But it is supposed to calculate the mean for each individual topic. I’m thinking maybe something with a counter for each meeting every time a user clicks on the stars, but I am not sure. And then maybe divide the stars with amount of votes/stars given
To get the mean of each section, you would need to capture each vote with a counter (can be stored in state or in plain text with # of votes) and divide the sum of all of the votes by the number of votes.
This can be done with an array of votes with each vote being added to an array every time a user clicks a rating, adding all the values in the array together, and dividing it by array.length.

Javascript counter controlled loop using (while) error

I am a newbie for java script programming. I want to print integers from 0 to 100. here is my code.
var outputAreaRef = document.getElementById("outputArea");
var i = 0; //Initialize counter
var number = 0;
while ( i <= 100) // Test Counter
{
number = number + 1 + "<br />";
i = i + 1; // Increment counter
outputAreaRef.innerHTML = number;
}
it prints digit 1 hundred times. but if i change the code like this,
number = number + i + ";
it will print from o to hundred. waht is the difference between the two codes?
thanks in advance
You are mixing strings with numbers. You need to do numerical computation in one variable and string concatenation in another. To increment number you can re-use i variable:
var outputAreaRef = document.getElementById('outputArea');
var i = 0;
var number = '';
while (i <= 100) {
i = i + 1; // numeric addition
number = number + i + '<br />'; // string concatenation
}
outputAreaRef.innerHTML = number; // it is ok to set html content only once
The code doesn't work because your output is number, and number is never changed and will remain as 0 because in the while loop, only i is changed.
Also change :
outputAreaRef.innerHTML = number;
to
outputAreaRef.innerHTML = outputAreaRef.innerHTML + number;
so that the whole innerhtml of the output area will not be replaced every loop.
Modify your while loop and it will work perfectly:
while ( i <= 100) {
number = i + 1 + "<br />";
i = i + 1; // Increment counter
outputAreaRef.innerHTML = outputAreaRef.innerHTML + number;
}
Working fiddle
var number became a String after first run and digit 1 concat to number afterward.

Checking random number variable against Javascript array values for match, not working

For the sake of learning (I am very much a beginner), I am trying to write a function with that will generate random numbers according to three user inputed variables. The user can input how many random numbers to generate
var count = 10;
which numbers to avoid generating (seperated by commas)
var doNotInclude = (document.getElementById("doNotIncludeInput").value).split(",");
and what the highest number possible should be
var highestNumber = 10;
In theory, if the user inputed "1,2" for the doNotInclude variable, the function should create an array containing those two numbers and then each time it generates a random number, check it against the array to see if the number it generated is one of the numbers it isn't supposed to generate.
Unfortunately, it doesn't work. It creates the array as it should which I verified via console.log(), but it will still generate the numbers it isn't supposed to. Here's the full script:
document.getElementById("button").onclick = function() {
var total = 0,
average = 0,
random = 0,
count = parseInt(document.getElementById("countInput").value),
doNotInclude = document.getElementById("doNotIncludeInput").value).split(","),
highestNumber = parseInt(document.getElementById("highestNumberInput").value);
document.getElementById("text1").innerHTML = "";
for (var i = 0; i < count; i++) {
var proceed = false;
for (random = Math.floor(((Math.random()) * (highestNumber + 1))); proceed == false;) {
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
}
document.getElementById("text1").innerHTML = document.getElementById("text1").innerHTML + "<br />" + (i + 1) + ". " + random;
total = total + random;
if (i == (count - 1)) {
total / count;
document.getElementById("text").innerHTML = "Mean average = " + (Math.round(total / count));
}
}
}
The part that isn't working
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
the indexOf function, is something I read about on here, but I guess I don't fully understand it. By my understanding, it should check to see if any of the array values are the same as the random variable, and if not, then return "-1" and execute my code. It doesn't seem to be doing that though. I am super confused...would love some help. Is it possible the array is storing the numbers as strings instead of integers, and that is the problem?
Your if statement doesn't work because of coercion.
===-1
The array doNotInclude contains strings, but random is an integer value, === always compares value and type both.
You should either use ==. Or have the both types same.
Try this Fiddle
HTML
Count: <input id="countInput" value="10" /><br />
Do not include: <input id="doNotIncludeInput" value="0,1,2,3,4,5" /><br />
Highest Number: <input id="highestNumberInput" value="10" /><br />
<br />
<button type="button" id="button">Click to Run!</button><br />
<br />
Results:<br />
<div id="text1"></div>
Js
document.getElementById("button").onclick = function() {
var currentCount = 0;
var randomNumbers = [];
var count = parseInt(document.getElementById("countInput").value);
var doNotIncludeInput = document.getElementById("doNotIncludeInput").value.split(",");
var highestNumberInput = parseInt(document.getElementById("highestNumberInput").value);
var resultsElement = document.getElementById("text1");
resultsElement.innerHTML = "";
while(currentCount < count) {
var random = -1;
while(random === -1){
random = Math.floor((Math.random()) * (highestNumberInput + 1));
for(var i in doNotIncludeInput) {
if(parseInt(doNotIncludeInput[i]) === random){
random = -1;
}
}
if(random !== -1){
randomNumbers.push(random);
}
}
currentCount += 1;
}
resultsElement.innerHTML = randomNumbers.join(', ');
}

Javascript Averaging Calculator(Multiple Values entered by the user)

I want to be able to have a user enter multiple grades and then have the Javascript to average those grades that are entered. When the user is done entering grades, they can click cancel and close the Propmt Box, and if they don't enter any grades at all (defaults at 0), then the program displays that there were no grades entered.
I'm pretty new at this! I'm taking a javascript course at my College, and it's a bit confusing because the teacher doesn't teach! All we have to reference to is W3schools, which this stuff isn't listed at all!
Here's another explanation:
"Develop a program to allow a teacher to enter an arbitrary number of grades, perform an average calculation and then display the result in a grammatical sentence. The program must also tell the user if no grades were entered. You are required to use a loop and an “if else” statement. Be sure to declare all variables and test for the possibility of division by zero."
<script type = "text/javascript">
var gradeCounter = 0,
gradeValue = 0,
total = 0,
average, grade;
var sum = 0;
var i = 0;
while (gradeValue != -1 && gradeValue <= 100) {
//Prompt the user
grade = prompt("Enter Grades, -1 to Quit:", "0");
//Parse the prompt result to a int
sum += parseInt(grade);
i++;
if (i >= 0 && grade != null) {
document.getElementById("average").innerHTML = "The average of the grades you've entered are " + sum / i + ".";
} else {
document.getElementById("error").innerHTML = "There were no grades entered";
}
} </script>
Thanks again!
this does ok
updated
updated again
JSFIDDLE
// note: the dom must be ready before execution
var btn = document.querySelector('button'),
res = document.getElementById('average');
btn.addEventListener('click', function(e) {
var val = prompt('Enter comma delimited grades to average');
val = val.length ? val.replace(/\s/g, '').split(',') : '';
var count = val.length || 0; // no 0 division
if (!count) {
res.innerHTML = 'you must enter comma delimited numbers to average';
return;
} else {
var average = val.reduce(function(a, b) { // is a loop
return +a + +b;
});
res.innerHTML = (average /= count).toFixed(1);
}
});
html
<button id="avgBtn">Prompt</button>
<p>Average: <span id="average"></span></p>
var grades = [];
// initialize the array that will store the entries
var sum = 0;
// initialize the variable that will add the array values together
var average;
// initialize the variable that will contain the final result
var invalid = [];
// initialize the variable that will be used to make sure the user inserts something
for (i = 0; i < 5; i++) {
// repeat the following code 5 times
grades[i] = prompt("Please enter a grade. (You will be asked for 5 grades)", "");
// ask the user for a grade and store it to the array
}
for (i = 0; i < grades.length; i++) {
if (grades[i] === "" || grades[i] === null) {
invalid[invalid.length] = grades[i];
}
}
if (invalid.length !== 5) {
for (i = 0; i < grades.length; i++) {
// repeat this code the same amount of times as there are entries in the array (5)
sum += Number(grades[i]);
// add the entries together. make sure they are numbers using the Number() function
}
var average = sum / grades.length;
// divide the added entries by the number of entries (again, 5)
alert("The average of all of your numbers is: " + average);
// alert the user of the completed average
} else {
alert('You need to enter grades for this to work! Please reload the page to try again.');
}

Spelling game score points using javascript

I have a spelling game that uses JavaScript.
Currently when the word is spelled correctly it will display a message.
if(++score >= str.length) {
var text = 'Well done! The correct word is ' + str + '!'
drawBackground(background, images.back, text);
}
I would like to display one point for each correct word and increment it.
This is what i have tried but no luck
function points() {
var points = 0;
if(++score >= str.length) {
points++;
document.getElementById("points").innerText="Score: " + points;
}
}
The HTML to display the score
<p>Score: <span id="points"></span></p>
Problems with your code:
The value of points is being reset to 0 every time you enter the points() function. You must move var points = 0 outside of points(), making it a global variable.
As you cannot have a function and a global variable with the same name, you must rename the points variable (e.g. to numPoints).
The el.innerText property will only work on IE. Replace it el.textContent.
Improved version of your code:
let numPoints = 0;
function points() {
if(++score >= str.length) {
numPoints++;
document.getElementById("points").textContent = "Score: " + numPoints;
}
}

Categories