I'm trying to create a small maths game with the code below, however I keep getting Not-A-Number error everytime the prompt comes up. i'm not entirely sure what the problem is. I have tried to round the number but it doesn't help the situation. Could someone point me in the right direction?
function start() {
// define questions
var question = [];
// define answers
var answer = [];
// store user input
var input = [];
var score = 0;
// when the user enters their answer it is stored by input for every prompt
for(var i = 0; i < 10; i++) {
var randNum = Math.floor(Math.random() * 100);
var operator = [ '+', '-', '*', '/' ];
var ops = [Math.floor(Math.random() * operator.length)];
question[i] = randNum + ops[operator] + randNum;
answer[i] = randNum + ops[operator] + randNum;
input[i] = prompt(question[i]);
}
// check the answer against the stored answer, display one of either from if statement
for(var i = 0; i < answer.length; i++) {
if (answer[i] == input[i]) {
var outputResult = document.getElementById("write");
outputResult.innerHTML += "<p class = corr>Question " + (i+1) + " is correct.</p>";
} else {
outputResult.innerHTML += "<p class = incorr>Question " + (i+1) + " is incorrect. The answer should have been " + answer[i] + ".</p>";
}
}
}
<header>
<h1>Maths Game!</h1>
</header>
<button onclick="start()">Start</button> <!-- start game -->
<div id="write">
</div>
<div class="score"></div>
</div>
You reference the operator array incorrectly. Try this:
var operator = ['+', '-', '*', '/'];
var ops = Math.floor(Math.random() * operator.length);
question[i] = randNum + operator[ops] + randNum;
answer[i] = eval(question[i]);
input[i] = prompt(question[i]);
These two lines create NaN in each index of question/answer ARRAYs:
question[i] = randNum + ops[operator] + randNum;
answer[i] = randNum + ops[operator] + randNum;
Because:
ops[operator]
is not a Number;
Related
I'm having some problem with this function. I ask sorry if the code looks a bit confused.
Basically what i'm trying to do is to divide some elements between the top and bottom of the documents having between them the same space circa.
i wrote this code but seems like the first "for" cycle goes loop ever and ever again.
** update**
so i improved the code and now the problem seems to be the variable "ifc"(if-counter). It suppose to increase by one every time that one of the if or else if is completed , but as you can see on the console it always remain 0 .
anyone can help?
thanks
var sizewidth = window.innerWidth;
var sizeheight = 3000;
function initialPosition(){
var els = document.querySelectorAll('.ico');
var tb = Math.round(els.length * 0.4);
console.log(tb);
var lr = els.length - tb;
var distPixEachTopBottom = sizewidth / (tb/2);
console.log(distPixEachTopBottom);
var distPixEachLefRight = sizeheight / (lr/2);
var nextTop = 0;
var nextLeft = 0;
var nextBottom = 0;
var nextRight = 0 ;
for (i = 0; i < els.length; i++) {
var ifc = 0;
console.log('i' + i);
if(i < tb){
var sf = 0;
for(;;){
console.log('sf' + sf + 'tb ' + tb);
if(ifc > 1){
console.log('ifc'+ ifc);
ifc = 0;
break
}else if(ifc == 0){
els[i].style.top = 0 +'px';
els[i].style.left = nextTop + 'px';
console.log('ifc ' + ifc + 'i ' + i + 'nexttop' + nextTop)
nextTop = nextTop + distPixEachTopBottom;
ifc++;
break;
}else if(ifc == 1){
els[i].style.bottom = 0 +'px';
els[i].style.right = nextBottom + 'px';
console.log('ifc ' + ifc + 'i ' + i + 'nextbottom' + nextBottom)
nextBottom = nextBottom + distPixEachTopBottom;
ifc++;
break;
}else{
console.log('else if problem')
break;
}
}
}else{
}
}
initialPosition();
update
i created a pen as you asked
codepen
So basically of all the boxes the 40% of them (6 in this case) should be divided between top and bottom but they go just on top.
So I solved by myself .
I put the var ifc before then any function .
Anyway thanks everyone
I need to assign instances of my object as values in my array, but when I try to add let to my loop for collecting user input, I get an error stating that "[" is an unexpected token. This is a new technique to me so I'm not sure if this is even a practical method for making a table. Any help is appreciated.
<script>
function generateTable() {
var tblStart = "<table>";
//This is the header line for my table.
var tblMeat = "<tr> <td><b>Name</b></td> <td><b>Attendance</b></td> <td><b>Homework</b></td> <td><b>Midterm</b></td> <td><b>Final</b></td> <td><b>Course Grade</b></td> <td><b>Round Grade</b></td> <td><b>Letter Grade</b></td> </tr>";
var tblStop = "</table>";
//This determines the number of rows.
var rowCount = prompt("How many students are in the class?");
//I want to assign instances of Student to this array which will be used to fill the table cells.
var pupil = [NUMBER(rowCount)];
//This object should process user entries and use them to calculate the total grade, rounded grade, and letter grade.
function Student(name, attendance, homework, mGrade, fGrade) {
this.name = name;
this.attend = attendance;
this.homewrk = homework;
this.midter = mGrade;
this.fingrad = fGrade;
this.course = function () {
var attGrade = this.attend * 0.1;
var hwkGrade = this.homewrk * 0.2;
var midGrade = this.midter * 0.3;
var finGrade = this.fingrad * 0.4;
var combGrade = attGrade + hwkGrade + midGrade + finGrade;
return combGrade.toFixed(2);
};
this.round = Math.round(this.course);
this.letter = function() {
if(this.course < 60) {
return '<p style="color:red;">F</p>';
} else if(this.course >= 60 && this.course <= 69.9){
return "D";
} else if(this.course >= 70 && this.course <= 79.9) {
return "C";
} else if(this.course >= 80 && this.course <= 89.9) {
return "B";
} else if(this.course >= 90 && this.course <= 100) {
return "A";
};
};
}
/*This loop should collect user input based on the declared number of students, and assign input values to instances of
Student based on which execution of the loop is being run. I am getting an error stating "[" is unexpected for line 79.
*/
for (var r = 0; r < rowCount; r++) {
var studentN = prompt("Enter student name.");
var studentA = prompt("Enter student attendance.");
var studentH = prompt("Enter student homework grade.");
var studentM = prompt("Enter student midterm grade.");
var studentF = prompt("Enter student final grade.");
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
}
for(var i = 0; i < rowCount; i++) {
tblMeat += "<tr>";
for(var j = 0; j < 8; j++) {
tblMeat += "<td>" + pupil[i].name + "</td><td>" + pupil[i].attend + "</td><td>" + pupil[i].homewrk + "</td><td>" + pupil[i].midter + "</td><td>" + pupil[i].fingrad + "</td><td>" + pupil[i].course() + "</td><td>" + pupil[i].round + "</td><td>" + pupil[i].letter() + "</td>";
}
tblMeat += "</tr>";
}
//This just puts it all together.
var completeTable = tblStart + tblMeat + tblStop;
document.getElementById("placetable").innerHTML = completeTable;
}
</script>
I ran your program through uglifyJS. It's actually for compressing javascript code, but when there is a lot of code to debug, it's a life changer.
The script told me:
Parse error: Unexpected token: punc ([)
Line 59, column 16
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
You're trying to define an already existing variable. Remove "let".
A tiny advice for the future.
I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>
The user should be able to enter in an integer and see the base, squared, and cubed result of that number. The base result should be listed under the "base" header, the squared result should be listed under the "squared" header and the cubed result should be listed under the "cubed" result. However, my output is listed all results under the "base" header. How can I make the results be listed under the related headers? This is what I have:
var $ = function (id) {
return document.getElementById(id);
}
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput;
for (var i = 1; i <= integer; i++) {
base += i + "\n";
squared += i * i + "\n";
cubed += i * i * i + "\n";
displayOutput = base + squared + cubed;
}
$("output").value = header + displayOutput;
}
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
}
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
}
It all depends on the output. Trying to stay as close as possible to your code, seems you are inserting your resulting displayOutput string into a textarea control. If you want to keep it that way, try tabs (\t) to separate your columns, and only a new line at the end (\n). Also, I noticed you were concatenating every column (base, square, and cubed) on every iteration, so I removed that. Here's the result:
var $ = function (id) {
return document.getElementById(id);
};
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput = "";
for (var i = 1; i <= integer; i++) {
base = i + "\t";
squared = i * i + "\t";
cubed = i * i * i + "\n";
displayOutput += base + squared + cubed;
}
$("output").value = header + displayOutput;
};
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
};
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
$("theform").onsubmit = function() { return false; };
};
So, i'm adding 2 characters 4 levels together (hp, attack, strength and defense) and then comparing them. However I am having a problem. when the numbers are added together they're added together as a string so it outputs as follows. 9060951/99709940 instead of 246 (90+60+95+1)/308 (99+70+99+40). Here is what I am doing.
function calculate(player1, player2) {
var total1 = player1.getTotal();
var total2 = player2.getTotal();
var differencePercentage;
if(total1 > total2) {
differencePercentage = total2 + "/" + total1 + " = " + (total2/total1);
} else {
differencePercentage = total1 + "/" + total2 + " = " + (total1/total2);
}
var percentage = differencePercentage;
return percentage;
}
function Player(hp, attack, strength, defense) {
this.hp = parseInt(hp);
this.attack = parseInt(attack);
this.strength = parseInt(strength);
this.defense = parseInt(defense);
this.getTotal = function() {
var total = 0;
total = hp + attack + strength + defense;
return total;
}
}
Why is this happening?
You are parsing the Ints into this.hp, this.attack etc. in your Player function but not into the getTotal function
Try this
this.getTotal = function() {
var total = 0;
total = this.hp + this.attack + this.strength + this.defense;
return total;
}