Hello I am trying to solve an exercise where we have to create a class Appliance and then two child classes (tv and washing machine), then I need to check the color and the consumption of the appliance, or their childs, and if none is passed it will be given a default value with a method. So far this is what I have but it keeps telling me this.checkcolor is not a function; I have tried the syntax also like this.color = checkColor(color) and also with constant giving the default values but nothing seems to work.
What would it be the easiest way to do this? Thanks
function Appliance(color, consumption, weight){
this.color = this.checkColor(color);
this.consumption = this.checkConsumption(consumption);
this.weight = weight || 5;
this.price = this.getPrice(this.consumption, this.weight);
Appliance.prototype.checkConsumption = function(consumption){
let res = "";
const consumptions = ["A", "B", "C", "D", "E", "F"];
for(let i = 0; i < consumptions; i++){
if(consumptions[i] == consumption){
res = consumption;
}
else{
res = "F";
}
}
return res
}
Appliance.prototype.checkColor = function(color){
let res = "";
let checker = false;
const colors = ["white", "red", "blue", "grey"];
for(let i = 0; i < colors.length && !checker; i++){
if(colors[i] == color){
checker = true;
}
}
if(checker){
res = color;
}
else{
res = "white";
}
return res;
}
Appliance.prototype.getPrice = function(consumption, weight){
let defaultPrice = 100;
let extra = 0;
switch(consumption){
case "A":
extra += 100;
break;
case "B":
extra += 80;
break;
case "C":
extra += 60;
break;
case "D":
extra += 50;
break;
case "E":
extra += 30;
break;
case "F":
extra += 10;
break;
}
if(weight >= 0 && weight < 19){
extra += 10;
}else if(weight >= 20 && weight < 49){
extra += 50;
}else if(weight >= 50 && weight <= 79){
extra += 80;
}else if(weight >= 80){
extra += 100;
}
return defaultPrice + extra;
}
Appliance.prototype.getColor = function(){
return this.color;
}
Appliance.prototype.getConsumption = function(){
return this.consumption;
}
Appliance.prototype.getWeight = function(){
return this.weight;
}
} ```
Related
I'm making a Wordle game with JavaScript. However, the ID in the UPDATE function doesn't work even though the ID I used before is full.
I tried changing the id, it didn't work. Because it returns
null Uncaught TypeError: Cannot read properties of null (reading
'innerText').
I am getting the error, and it tells me that the variable named rowCol is giving an error.
var height = 6;
var width = 5;
var row = 0;
var col = 0;
var gameOver = false;
var wordList = ["apple", "mango", "river", "hyped", "tokyo", "title", "ouija"];
var guessList = ["apple", "mango", "river", "hyped", "tokyo", "title", "ouija", "carbo", "proxy"];
guessList = guessList.concat(wordList);
var word = wordList[Math.floor(Math.random() * wordList.length)].toUpperCase();
console.log(word);
window.onload = function() {
initialize();
}
function initialize() {
for (let r = 0; r < height; r++) {
for (let c = 0; c < width; c++) {
let tile = document.createElement("span");
tile.id = r.toString() + "_" + c.toString();
tile.classList.add("tile");
tile.innerText = "";
document.getElementById("board").appendChild(tile);
}
}
//Keyboard
let keyboard = [
["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"],
["A", "S", "D", "F", "G", "H", "J", "K", "L", " "],
["Enter", "Z", "X", "C", "V", "B", "N", "M", "←"]
]
for (let i = 0; i < keyboard.length; i++) {
let currRow = keyboard[i];
let keyboardRow = document.createElement("div");
keyboardRow.classList.add("keyboard-row");
for (let j = 0; j < currRow.length; j++) {
let keyTile = document.createElement("div");
let key = currRow[j];
keyTile.innerText = key;
if (key == "Enter") {
keyTile.id = "Enter";
} else if (key == "←") {
keyTile.id = "Backspace";
} else if ("A" <= key && key <= "Z") {
keyTile.id = "Key" + key;
}
keyTile.addEventListener("click", processKey);
if (key == "Enter") {
keyTile.classList.add("enter-key-tile");
} else {
keyTile.classList.add("key-tile");
}
keyboardRow.appendChild(keyTile);
}
document.body.appendChild(keyboardRow);
}
document.addEventListener("keyup", (e) => {
processInput(e);
})
}
function processKey() {
e = {
"code": this.id
};
processInput(e);
}
function processInput(e) {
if (gameOver) return;
if ("KeyA" <= e.code && e.code <= "KeyZ") {
if (col < width) {
let currTile = document.getElementById((row + '_' + col));
console.log(currTile)
// console.log(currTile.innerText.length);
// console.log((row.toString() + '_' + col.toString()));
// console.log(e.code);
if (currTile.innerText == "") {
currTile.innerText = e.code[3];
col += 1
}
}
} else if (e.code == "Backspace") {
if (0 < col && col <= width) {
col -= 1;
}
let currTile = document.getElementById((row + '_' + col));
currTile.innerText = '';
// console.log(currTile);
} else if (e.code == "Enter") {
update()
// console.log(update());
}
if (!gameOver && row == height) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
}
function update() {
var guess = "";
document.getElementById("answer").innerText = "";
console.log(row);
console.log(col);
for (let c = 0; c < width; c++) {
let rowCol = document.getElementById((row + '_' + col));
// // if(currTile ===null){
// // alert("BOŞ DEĞER UYARISI");
// // }
letter = rowCol.innerText;
console.log(guess);
guess += letter;
}
guess = guess.toLowerCase();
console.log(guess);
if (!guessList.includes(guess)) {
document.getElementById("answer").innerText = "Not in word list";
return;
}
let correct = 0;
let letterCount = {};
for (let i = 0; i < word.length; i++) {
let letter = word[i];
if (letterCount[letter]) {
letterCount[letter] += 1;
} else {
letterCount[letter] = 1;
}
}
//console.log(letterCount);
for (let c = 0; c < width; c++) {
let currTile = document.getElementById((row + '_' + col));
let letter = currTile.innerText;
if (word[c] == letter) {
currTile.classList.add("correct");
let keyTile = document.getElementById("Key" + letter);
keyTile.classList.remove("present");
keyTile.classList.add("correct");
correct += 1;
letterCount[letter] -= 1;
}
if (correct == width) {
gameOver = true;
}
}
// console.log(letterCount);
for (let c = 0; c < width; c++) {
let currTile = document.getElementById((row + '_' + col));
let letter = currTile.innerText;
if (!currTile.classList.contains("correct")) {
if (word.includes(letter) && letterCount[letter] > 0) {
currTile.classList.add("present");
let keyTile = document.getElementById("Key" + letter);
if (!keyTile.classList.contains("correct")) {
keyTile.classList.add("present");
}
letterCount[letter] -= 1;
} else {
currTile.classList.add("absent");
let keyTile = document.getElementById("Key" + letter);
keyTile.classList.add("absent");
}
}
}
row += 1;
col = 0;
}
I've looked through the JavaScript threads again but haven't found an answer yet. Thanks a lot for your help.
Problem appears when length of user input is equal to length of input word.
After inputting a last letter this code makes col = 5 in "processInput()" function:
col+=1
Then update() is being invoked and there is addressing to unexisted element:
let rowCol = document.getElementById((row + '_' + col));
There is no column with index of 5, because there are only 5 columns with indexes from 0 through 4.
Adding --col; like that:
function update() {
var guess = "";
document.getElementById("answer").innerText = "";
--col; // <-- add this here
console.log(row);
console.log(col);
should be enough.
I've made a meteor "game". On window load I set my shield:
window.onload = function() {
document.getElementById("shield").innerHTML = "Max";
var playStart = document.getElementById("playBtn");
playStart.addEventListener("click", playGame);
}
On a click of the play button I'm calling a function (playGame) to loop (currently 20 odd times). In this loop I call my meteor create function (called setUp):
function playGame() {
for (i = 0; i < 21; i++) {
if (document.getElementById("shield").innerHTML != "End") {
setUp();
} else {
continue;
}
}
}
In setup I create the meteor and animate it. I've added an event listener so that on the animation's end (i.e. the "player" hasn't destroyed the meteor) it calls a function to remove the meteor and change the shield status:
function setup() {
imgMeteor.addEventListener("animationend", imgEnd);
// This function (imgEnd is within my setUp function).
function imgEnd() {
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
var currShield = document.getElementById("shield").innerHTML;
switch (currShield) {
case "Max":
currShield = "Med";
break;
case "Med":
currShield = "Min";
break;
case "Min":
currShield = "None";
break;
case "None":
currShield = "End";
break;
}
document.getElementById("shield").innerHTML = currShield;
if (currShield == "End") {
return;
}
}
}
(I've tried to show just the relevant code). How can I stop the loop running. (Basically I want the game to end once the barrier is "End"?
Any help would be awesome. Entire code below if that helps.
var numText = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine"
];
var modText = ["0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"];
window.onload = function() {
document.getElementById("shield").innerHTML = "Max";
var arrNum = 0;
document.getElementById("spdText").innerHTML = numText[arrNum];
myNum = arrNum;
var upSpd = document.getElementById("upBtn");
upSpd.addEventListener("click", nextyNum);
var downSpd = document.getElementById("downBtn");
downSpd.addEventListener("click", prevyNum);
var playStart = document.getElementById("playBtn");
playStart.addEventListener("click", playGame);
var playPause = document.getElementById("pauseBtn");
playPause.addEventListener("click", pauseGame);
}
function nextyNum() {
myNum += 1;
if (myNum <= 9) {
document.getElementById("spdText").innerHTML = numText[myNum];
document.getElementById("warpProg").value = [myNum];
document.getElementById("currMod").innerHTML = modText[myNum]
} else {
alert("She cannie take any more cap'n. Speed's at maximum");
}
if (myNum > 9) {
myNum = 9;
}
progColourCheck();
}
function prevyNum() {
myNum -= 1;
if (myNum >= 0) {
document.getElementById("spdText").innerHTML = numText[myNum];
document.getElementById("warpProg").value = [myNum];
document.getElementById("currMod").innerHTML = modText[myNum];
} else {
alert("She's as low as she can go cap'n ");
}
if (myNum < 0) {
myNum = 0;
}
progColourCheck();
}
function progColourCheck() {
var progColours = ["lightgrey", "lightyellow", "yellow", "greenyellow", "lawngreen", "#73e600",
"#cc9900", "orange", "orangered", "red"
];
document.getElementById("warpProg").style.color = progColours[myNum];
document.getElementById("currMod").style.backgroundColor = progColours[myNum];
}
function playGame() {
var tempScore = document.getElementById(currScore);
tempScore = parseInt(currScore.innerHTML);
var hiScore = document.getElementById(hScore);
hiScore = parseInt(hScore.innerHTML);
if (tempScore > hiScore) {
hScore.innerHTML = tempScore;
}
currScore.innerHTML = 0000;
if (myNum == 0) {
alert("The ship's not movin' cap'n");
return;
}
for (i = 0; i < 21; i++) {
if (document.getElementById("shield").innerHTML != "End") {
document.getElementById("upBtn").disabled = "true";
document.getElementById("downBtn").disabled = "true";
setUp();
} else {
continue;
}
}
document.getElementById("titleText").style.visibility = "hidden";
document.getElementById("playBtn").style.visibility = "hidden";
}
function setUp() {
var imgMeteor = document.createElement("p");
var blankNode = document.createTextNode("");
imgMeteor.appendChild(blankNode);
document.getElementById("canvas").appendChild(imgMeteor);
imgMeteor.style.visibility = "hidden";
imgMeteor.style.backgroundImage = 'url("meteor.gif")';
imgMeteor.style.width = "56px";
imgMeteor.style.height = "56px";
imgMeteor.style.position = "absolute";
imgMeteor.addEventListener("mouseover", removeElement);
imgMeteor.style.animationName = "animBlock";
imgMeteor.style.animationDuration = 10 - myNum + "s";
imgMeteor.style.animationDelay = Math.floor(Math.random() * (8 - 0 + 1)) + 0 + "s";
imgMeteor.style.animationTimingFunction = "linear";
imgMeteor.addEventListener("animationstart", imgVis);
function imgVis() {
imgMeteor.style.visibility = "visible";
}
imgMeteor.addEventListener("animationend", imgEnd);
var leftPos = xPosition(0);
imgMeteor.style.left = leftPos + "%";
var topPos = yPosition(0);
imgMeteor.style.top = topPos + "px";
function removeElement() {
var cScore = document.getElementById("CurrScore");
cScore = parseInt(currScore.innerHTML);
cScore += (1 * myNum);
currScore.innerHTML = cScore;
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
document.getElementById("barrier").style.background = "linear-gradient(darkblue, lightblue)";
}
function imgEnd() {
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
document.getElementById("barrier").style.background = "linear-gradient(red, orange)";
var cScore = document.getElementById("CurrScore");
cScore = parseInt(currScore.innerHTML);
var negScore = myNum;
if (negScore > 1) {
negScore -= 1;
}
cScore -= (1 * negScore);
currScore.innerHTML = cScore;
var currShield = document.getElementById("shield").innerHTML;
switch (currShield) {
case "Max":
currShield = "Med";
break;
case "Med":
currShield = "Min";
break;
case "Min":
currShield = "None";
document.getElementById("bubble").style.visibility = "hidden";
break;
case "None":
currShield = "End";
break;
}
document.getElementById("shield").innerHTML = currShield;
if (currShield == "End") {
return;
}
}
}
function xPosition(lPos) {
var lPos = Math.floor(Math.random() * (90 - 1 + 1)) + 1;
return lPos;
}
function yPosition(tPos) {
var tPos = Math.floor(Math.random() * (80 - 10 + 1)) + 10;
return tPos;
}
function pauseGame() {
playBtn.style.visibility = "visible";
document.getElementById("upBtn").disabled = "false";
document.getElementById("downBtn").disabled = "false";
document.getElementById("shield").innerHTML = "Max";
}
Your loop should look like this then:
function playGame() {
for (i=0; i < 21; i++) {
if (document.getElementById("shield").innerHTML == "End"){
break;
}
SetUp();
}
}
You want to break the loop when the condition is met.
We are using createJS and right now I am struggling with a hit test.
I get this error:
"ss.js:203 Uncaught TypeError: Cannot read property 'x' of undefined
at hitTest (ss.js:203)
at doCollisionChecking (ss.js:215)
at heartBeat (ss.js:238)
at Function.b._dispatchEvent (createjs-2015.11.26.min.js:12)
at Function.b.dispatchEvent (createjs-2015.11.26.min.js:12)
at Function.a._tick (createjs-2015.11.26.min.js:12)
at a._handleTimeout (createjs-2015.11.26.min.js:12)"
I think the problem has to the with the 2 objects x position, but one is a player controlled character and the other object have random x value.
All the hit test example i found always consist of a static object and a moving, but this time they are both moving and i have no idea what to do.
var stage, hero, queue, circle, coin;
var coins = [];
var Score, tekst1, tekst2;
var speed = 3;
var keys = {
u: false,
d: false,
l: false,
r: false
};
var settings = {
heroSpeed: 15
};
function preload() {
"use strict";
stage = new createjs.Stage("ss");
queue = new createjs.LoadQueue(true);
queue.installPlugin(createjs.Sound);
queue.loadManifest([
{
id: 'Vacuum',
src: "img/Vacuum.png"
},
{
id: 'Dust',
src: "img/dust.png"
},
{
id: 'Pickup',
src: "sounds/pickup.mp3"
},
{
id: 'Suger',
src: "sounds/suger.wav"
},
]);
queue.addEventListener('progress', function () {
console.log("hi mom, preloading");
});
queue.addEventListener('complete', setup);
}
function setup() {
"use strict";
window.addEventListener('keyup', fingerUp);
window.addEventListener('keydown', fingerDown);
circle = new createjs.Bitmap("img/Vacuum.png");
circle.width = 40;
circle.height = 90;
stage.addChild(circle);
circle.y = 570;
circle.x = 460;
Score = new createjs.Text("0", "25px Impact", "white");
Score.x = 900;
Score.y = 680;
Score.textBaseline = "alphabetic";
stage.addChild(Score);
tekst1 = new createjs.Text("Score", "25px Impact", "white");
tekst1.x = 740;
tekst1.y = 680;
tekst1.textBaseline = "alphabetic";
stage.addChild(tekst1);
tekst2 = new createjs.Text("Bombs fallin", "40px Impact", "white");
tekst2.x = 10;
tekst2.y = 50;
tekst2.textBaseline = "alphabetic";
stage.addChild(tekst2);
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick', heartBeat)
}
function addCoins() {
coin = new createjs.Bitmap("img/dust.png");
coin.x = Math.random() * 900;
coin.width = 36;
coin.height = 50;
coins.push(coin);
stage.addChild(coin);
}
function moveCoins() {
for (var i = 0; i < coins.length; i++) {
coins[i].y += speed;
}
for (var j = 0; j < coins.length; j++) {
if (coins[j].y > 650) {
console.log("hejsa");
stage.removeChild(coins[j]);
coins.splice(j, 1);
}
}
}
function maybeAddCoin() {
var rand = Math.random() * 500;
if (rand < 5) {
addCoins();
}
}
function fingerUp(e) {
"use strict";
//createjs.Sound.stop("Suger")
switch (e.keyCode) {
case 37:
keys.l = false;
break;
case 38:
keys.u = false;
break;
case 39:
keys.r = false;
break;
case 40:
keys.d = false;
break;
}
}
function fingerDown(e) {
"use strict";
switch (e.keyCode) {
case 37:
keys.l = true;
break;
case 38:
keys.u = true;
break;
case 39:
keys.r = true;
break;
case 40:
keys.d = true;
break;
}
}
function moveSlime() {
"use strict";
if (keys.l) {
circle.x -= settings.heroSpeed;
if (circle.x < 0) {
circle.x = 0;
}
if (circle.currentDirection != "left") {
circle.currentDirection = "left";
//createjs.Sound.play("Suger");
keys.u = false;
keys.r = false;
keys.d = false;
}
}
if (keys.r) {
circle.x += settings.heroSpeed;
if (circle.x > 960) {
circle.x = 960;
}
if (circle.currentDirection != "right") {
circle.currentDirection = "right";
//createjs.Sound.play("Suger")
keys.u = false;
keys.l = false;
keys.d = false;
}
}
}
function hitTest(rect1, rect2) {
if (rect1.x >= rect2.x + rect2.width || rect1.x + rect1.width <= rect2.x ||
rect1.y >= rect2.y + rect2.height || rect1.y + rect1.height <= rect2.y)
{
return false;
}
return true;
}
function doCollisionChecking() {
for (var k = coins.length - 1; k >= 0; k--) {
if (hitTest(circle, coin[k])) {
console.log("ramt");
}
}
}
function scoreTimer() {
//Score.text = parseInt(Score.text + 10);
}
function heartBeat(e) {
"use strict";
doCollisionChecking()
maybeAddCoin()
//addCoins()
moveCoins()
scoreTimer()
moveSlime()
stage.update(e);
}
window.addEventListener('load', preload);
Clearly one of your elements is undefined (either circle or coins[k]). I would start with figuring out which one.
Open your debugger.
Turn on "Pause on Exceptions" and re-run your code. When the error happens, your debugger will pause and you can inspect your code
Determine what is undefined. This should shed some light on what is causing the error
One important thing I noticed is that you are looking for rect.width when collision checking. EaselJS elements don't have a width property, so you should instead use getBounds(), which will work with Bitmaps once they are loaded.
// Example
var bounds = rect.getBounds();
var w = bounds.width, h = bounds.height;
Hope that helps!
Here's the problem:
function doCollisionChecking() {
for (var k = coins.length - 1; k >= 0; k--) {
if (hitTest(circle,
coin[k] // your array is coins, not coin
)) {
console.log("ramt");
}
}
}
It might help you in the future to pass arguments through the function instead of relying on global objects. They help you by keeping modifications to your data on tight track. With global variables, anything can modify coins from anywhere and you won't be able to tell what function it is if you have 50+ different functions editing that variable.
// CONFIG ////////////////
var initialBetAmount = 2;
var mode = 'martingale'; // can be 'martingale' or 'anti-martingale' (WAT? https://en.wikipedia.org/wiki/Martingale_(betting_sys.. )
var betColor = 'black'; // can be 'red' or 'black'
//////////////////////////
function tick() {
var a = getStatus();
if (a !== lastStatus && "unknown" !== a) {
switch (a) {
case "waiting":
bet();
break;
case "rolled":
rolled()
}
lastStatus = a, printInfo()
}
}
function checkBalance() {
return getBalance() - 1
}
function getColor(a) {
return 0 == a ? "green" : a >= 1 && 7 >= a ? "red" : "black"
}
function wonLastRoll() {
return lastBetColor ? lastRollColor === lastBetColor : null
}
var currentBetAmount = initialBetAmount,
currentRollNumber = 1,
lastStatus, lastBetColor, lastRollColor, $balance = $("#balance"),
$betAmountInput = $("#betAmount"),
$statusBar = $(".progress #banner"),
$redButton = $("#panel1-7 .betButton"),
$blackButton = $("#panel8-14 .betButton"),
refreshIntervalId = setInterval(tick, 500);
This is the code. The code works with csgodouble.com and bets on only one color and i want it to choose a random one instead. red/black
Since you don't provide much details, my guess is that this is what you need:
function getRandomColor(){
return Math.round(Math.random()) ? 'red' : 'black';
}
A random color you can generate like that:
function randColor() {
var col = "";
var possible = "ABCDEF1234567890";
for( var i=0; i < 6; i++ )
col += possible.charAt(Math.floor(Math.random() * possible.length));
return "#" + col;
}
I need help integrating classes and functions into an HTML page using JavaScript. I am not sure how to properly create an object and call its function(i.e.)
function calculateGrade(){
var x1 = document.forms["myForm"]["fname"].value;
var x2 = document.forms["myForm"]["lname"].value;
var x3 = document.forms["myForm"]["hwork"].value;
var x4 = document.forms["myForm"]["awork"].value;
var x5 = document.forms["myForm"]["midscore"].value;
var x6 = document.forms["myForm"]["midgrade"].value;
var x7 = document.forms["myForm"]["finscore"].value;
var x8 = document.forms["myForm"]["fingrade"].value;
var p1 = new Student(
x1,x2,[x3],[x4],x5,x6,x7,x8
); //creates it
document.getElementById("myForm").style.visibility="hidden";
document.getElementById("text").style.visibility="hidden";
alert(p1.getGrade()); //calls one of its methods
return false;
}
I am also unsure how to properly use classes in JS. I want the classes to be private while the methods are privileged.
function Student(){
function Student(firstName,lastName,hScore,aScore,mScore,mGrade,fScore,fGrade){
this.firstName = firstName;
this.lastName = lastName;
this.homework = new Coursework();
this.inClass = new Coursework();
this.studentsFinal = new Exam(fScore,fGrade);
this.studentsMidterm = new Exam(mScore,mGrade);
var that = this;
function setMidterm(mScore, mGrade){
that.studentsMidterm = new Exam(mScore, mGrade);
}
this.setMidterm = function() { // privileged method
setMidterm(mScore, mGrade);
}
function setFinal( fScore, fGrade){
that.studentsFinal = new Exam(fScore, fGrade);
}
this.setFinal = function() { // privileged method
setFinal( fScore, fGrade);
}
function addGradedHomework(hScore){
that.homework.addScore(hScore);
}
this.addGradedHomework = function() { // privileged method
addGradedHomework(hScore);
}
function addGradedActivity(aScore){
that.inClass.addScore(aScore);
}
this.addGradedActivity = function() { // privileged method
addGradedActivity(aScore);
}
this.printGrade=printGrade;
function getGrade(){
var letterGrade;
var weightCourse = ( (that.inClass.meanScore() * .15) + (that.homework.meanScore() * .25) + (that.studentsMidterm.getExamScore() * .25) + (that.studentsFinal.getExamScore() * .35) );
if (that.studentsMidterm.getExamScore() >= that.studentsFinal.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = studentsFinal.getExamGrade();
else if (that.studentsFinal.getExamScore() >= that.studentsMidterm.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = that.studentsFinal.getExamGrade();
else{
if (90.00 <= weightCourse){
letterGrade = "A";
}
else if( 80 <= weightCourse && weightCourse < 90){
letterGrade = "B";
}
else if (70 <= weightCourse && weightCourse < 80){
letterGrade = "C";
}
else if (60 <= weightCourse && weightCourse < 70){
letterGrade = "D";
}
else{
letterGrade = "F";
}
}
return letterGrade;
}
this.getGrade = function() { // privileged method
getGrade();
}
}
}
function Coursework(){
var sumScore;
var numScore;
function addScore(score){
numScore++;
if (score > 100)
sumScore = sumScore + 100;
else if ( score < 0)
sumScore = sumScore + 0;
else
sumScore = sumScore + score;
}
function meanScore(){
if (numScore == 0){
return 0.0;
}
else{
return (sumScore / numScore);
}
}
}
function Exam() {
var examScore;
var examGrade;
function Exam(score,grade ){
if (examScore < 0){
examScore = 0;
}
else if (examScore > 100){
examScore = 100;
}
else {
examScore = score;
}
switch (grade) {
case "A":
examGrade = "A";
break;
case "B":
examGrade = "B";
break;
case "C":
examGrade = "C";
break;
case "D":
examGrade = "D";
break;
case "F":
examGrade = "F";
break;
default:
examGrade = "F";
}
}
function getExamScore(){
return examScore;
}
function getExamGrade(){
return examGrade;
}
}
Any help is appreciated. If this does not make since let me know, I wasn't quite sure how to word it.
<html>
<title> Assignment 7 </title>
<h1> Students's Assignment 7 </h1>
<head>
<script type="text/javascript">
function calculateGrade(){
var x1 = document.forms["myForm"]["fname"].value;
var x2 = document.forms["myForm"]["lname"].value;
var x3 = document.forms["myForm"]["hwork"].value;
var x4 = document.forms["myForm"]["awork"].value;
var x5 = document.forms["myForm"]["midscore"].value;
var x6 = document.forms["myForm"]["midgrade"].value;
var x7 = document.forms["myForm"]["finscore"].value;
var x8 = document.forms["myForm"]["fingrade"].value;
var p1 = new Student(
x1,x2,[x3],[x4],x5,x6,x7,x8
);
//console.log(p1.getGrade());
//alert(x1);
document.getElementById("myForm").style.visibility="hidden";
document.getElementById("text").style.visibility="hidden";
alert(p1.getGrade());
return false;
}
function Student(){
function Student(firstName,lastName,hScore,aScore,mScore,mGrade,fScore,fGrade){
this.firstName = firstName;
this.lastName = lastName;
this.homework = new Coursework();
this.inClass = new Coursework();
this.studentsFinal = new Exam(fScore,fGrade);
this.studentsMidterm = new Exam(mScore,mGrade);
var that = this;
function setMidterm(mScore, mGrade){
that.studentsMidterm = new Exam(mScore, mGrade);
}
this.setMidterm = function() { // privileged method
setMidterm(mScore, mGrade);
}
function setFinal( fScore, fGrade){
that.studentsFinal = new Exam(fScore, fGrade);
}
this.setFinal = function() { // privileged method
setFinal( fScore, fGrade);
}
function addGradedHomework(hScore){
that.homework.addScore(hScore);
}
this.addGradedHomework = function() { // privileged method
addGradedHomework(hScore);
}
function addGradedActivity(aScore){
that.inClass.addScore(aScore);
}
this.addGradedActivity = function() { // privileged method
addGradedActivity(aScore);
}
this.printGrade=printGrade;
function getGrade(){
var letterGrade;
var weightCourse = ( (that.inClass.meanScore() * .15) + (that.homework.meanScore() * .25) + (that.studentsMidterm.getExamScore() * .25) + (that.studentsFinal.getExamScore() * .35) );
if (that.studentsMidterm.getExamScore() >= that.studentsFinal.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = studentsFinal.getExamGrade();
else if (that.studentsFinal.getExamScore() >= that.studentsMidterm.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = that.studentsFinal.getExamGrade();
else{
if (90.00 <= weightCourse){
letterGrade = "A";
}
else if( 80 <= weightCourse && weightCourse < 90){
letterGrade = "B";
}
else if (70 <= weightCourse && weightCourse < 80){
letterGrade = "C";
}
else if (60 <= weightCourse && weightCourse < 70){
letterGrade = "D";
}
else{
letterGrade = "F";
}
}
return letterGrade;
}
this.getGrade = function() { // privileged method
getGrade();
}
}
}
function Coursework(){
var sumScore;
var numScore;
function addScore(score){
numScore++;
if (score > 100)
sumScore = sumScore + 100;
else if ( score < 0)
sumScore = sumScore + 0;
else
sumScore = sumScore + score;
}
function meanScore(){
if (numScore == 0){
return 0.0;
}
else{
return (sumScore / numScore);
}
}
}
function Exam() {
var examScore;
var examGrade;
function Exam(score,grade ){
if (examScore < 0){
examScore = 0;
}
else if (examScore > 100){
examScore = 100;
}
else {
examScore = score;
}
switch (grade) {
case "A":
examGrade = "A";
break;
case "B":
examGrade = "B";
break;
case "C":
examGrade = "C";
break;
case "D":
examGrade = "D";
break;
case "F":
examGrade = "F";
break;
default:
examGrade = "F";
}
}
function getExamScore(){
return examScore;
}
function getExamGrade(){
return examGrade;
}
}
</script>
</head>
<body bgcolor="#81F79F">
<b id="text">Enter you information below</b>
<form id="myForm" onsubmit="return calculateGrade();" >
First name: <br><input type="text" id="element_1_1" name="fname"><br>
Last name: <br><input type="text" id="element_1_2" name="lname"><br>
Homework: <br><input type="text" id="element_1_3" name="hwork"><br>
Activity: <br><input type="text" id="element_1_4" name="awork"><br>
Midterm Score: <br><input type="text" id="element_1_5" name="midscore"><br>
Midterm Grade: <br><input type="text" id="element_1_6" name="midgrade"><br>
Final Score: <br><input type="text" id="element_1_7" name="finscore"><br>
Final Grade: <br><input type="text" id="element_1_8" name="fingrade"><br>
<input type="submit" value="Submit">
</form>
<div id="stuff"></div>
</body>
</html>