Problems with University code on JavaScript - javascript

I'm currently attempting to complete my university coursework but I'm struggling to get my code to work. Can someone give me a helping hand?
Now update your program so that the work of checking the lottery
result is done by a function called checkNumbers(). This function
should take the customer number and the array of winning numbers as
arguments. The customer number should be returned from a function
called getCustomerNumber(). The array of winning numbers should be
returned from a function called getWinningNumbers(). The display of
the results should be done by a function called displayResult(). The
whole process should be kicked off by a function called init().
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="lottotask5.js">
</script>
<meta charset="utf-8">
<title>DCSIS JavaScript Module TMA</title>
</head>
<body>
</body>
</html>
function init() {
new checkNumbers();
new displayResult();
new getWinningNumbers();
new getCustomerNumbers();
}
function getWinningNumbers(){
var winningNumbers = [12,17,24,37,38,43];
return winningNumbers;
}
function getCustomerNumbers(){
var customerNumbers = 12;
return customerNumbers;
}
function checkNumbers(customerNumbers, winningNumbers){
match == false;
for ( var i = 0; i < this.winningNumbers.length; i++){
if (this.customerNumbers == this.winningNumbers[i]){
match == true;
}
}
return match;
}
function displayResult(){
if(match == true){
alert("This Week's Winning Numbers are:\n\n" + winningNumbers[0]
+", "+ winningNumbers[1] +", "+
winningNumbers[2] +", "+ winningNumbers[3] +", "+
winningNumbers[4] +", "+ winningNumbers[5] +
"\n\n The Customer's Number is:\n\n" + customerNumbers + "\n\n
We have a match and a winner!");
}
else
{
alert("This Week's Winning Numbers are:\n\n" + winningNumbers[0]
+", "+ winningNumbers[1] +", "+
winningNumbers[2] +", "+ winningNumbers[3] +", "+
winningNumbers[4] +", "+ winningNumbers[5] +
"\n\n The Customer's Number is:\n\n" + 13 + "\n\n Sorry you are
not a winner this week.");
}
}

Function displayResults cannot see members of array winningNumbers. You have to call function getWinningNumbers() from displayResult() to obtain a list of winning numbers. Same goes for customernumbers and all variables that are not global.
https://www.w3schools.com/js/js_scope.asp

Related

Javascript: Having issues calling function(Cannot read property 'value' of null)

So i've been trying to debug this for a few hours and I'm completely stuck. When I go on the webpage I get this error in the console:
(Cannot read property 'value' of null at totalCost (assn1.html:18) at assn1.html:26 totalCost # assn1.html:18
(anonymous) # assn1.html:26.
My program is all finished I just can't get it to call the function and print the name, number of cups and the total cost at the end.
Heres my code:
<html>
<head>
<title>Tea Shoppe</title>
</head>
<body>
<section>
<h1> Welcome to the Tea Shoppe!</h1>
<p>
<img src = "http://nobacks.com/wp-content/uploads/2014/11/Tea-Cup-5-500x476.png" />
</p>
</section>
<script>
function totalCost()
{
var cups = parseInt(document.getElementById("cups").value);
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
totalCost(cups);
document.write("Ok" + name + ", you ordered" + cups + " of tea" + "your total price is" + totalCost);
</script>
</body>
</html>
document.getElementById("cups")
You have no element with that ID in your document.
function totalCost(cups)
{
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
document.write("Ok " + name + ", you ordered" + cups + " of tea" + " your total price is " + totalCost(cups));
Here's a working version of your code, what i did here is adding teh totalcost function parameter since you pass it when you call the function and got rid of the cups variable inside your function because it has nothing to do there and was causing an error also + and changed the place where you function should be called from since it returns the totalcups value it must be put inside the document.write function to return the total in it's perfect place.
that's all and i hope this fixed your problem.
herre's a working fiddle https://jsfiddle.net/bgn4x7ej/

Error in declaring array JavaScript?

Working through an intro JS coursera course. I'm making a simple color guessing game. I've inserted a few alerts at the beginning for troubleshooting, but I can't get this program to get reach the alert("test1"); line in my playGame, which is loading immediately through the body element. Any ideas what I'm doing wrong? I seem to be declaring it just fine...
<!DOCTYPE html>
<html>
<body onload="playGame()">
<p>Welcome to my color guessing game</p>
<script language = "JavaScript">
function inArray(needle, haystack){
for (var i = 0; i <haystack.length(); i++){
if (needle === haystack[i]){
return true;
}
}
return false;
}
function changeBackground(color){
document.body.style.background = color;
}
function playGame(){
var correct = false;
alert("Correct status is: " + correct);
var colorArray = ["cyan", "gold", "green", "gray", "magenta", "blue", "red", "orange", "yellow", "white"];
alert("test1");
for (var i = 0; i < colorArray.length(); i++){
alert("for " + i + " the color is " + colorArray[i]);
}
colorArray = colorArray.sort();
alert("answer index is " + answerIndex);
alert("color array length is " + colorArray.length());
var answerIndex = Math.floor(Math.random()*colorArray.length());
alert("the resulting color from the color array is: " + answerColor);
var answerColor = colorArray[answerIndex];
alert("The correct color is " + answerColor);
var answerList = colorArray.join(", ");
var guessCount = 0;
while(!correct){
var colorGuess = prompt("Welcome to my guessing game! The colors available for your choosing are: " + "\n\n" + answerList + "\n\n" + "Which color am I thinking of?");
guessCount++;
if (!inArray(colorGuess, colorArray)){
alert("Your guess wasn't one of the selections that was available or I otherwise don't recognize it." + "\n\n" + "Please try again!");
}
else{
if (colorArray.indexOf(colorGuess)<color.indexOf(answerColor)){
alert("Your guess was alphabetically before the correct color! Try again.");
}
else if (colorARray.indexOf(colorguess)>color.indexOf(answerColor)){
alert("Your guess was alphabetically after the correct color! Try again.");
}
else{
alert("Your guess is correct!");
correct = true;
changeBackground(answerColor);
}
}
}
alert("Great job!" + "\n\n" + "You took " + guessCount + " guesses to get the correct answer!");
}
</script>
</body>
</html>
I've just tested your code.
alert("answer index is " + answerIndex);
alert("color array length is " + colorArray.length());
var answerIndex = Math.floor(Math.random()*colorArray.length());
alert("the resulting color from the color array is: " + answerColor);
var answerColor = colorArray[answerIndex];
alert("The correct color is " + answerColor);
Here you're trying to alert the variable answerIndex, before you declare it.
In JS length is a property which returns the number of elements in an array. MDN Array Length.
In colorArray.length() replace length() by length.

JavaScript beginner variable confusion

Learning JS from a book, the exercise question was this:
Modify the code of Question 1 to request the times table to be displayed from the user; the code
should continue to request and display times tables until the user enters ‐1. Additionally, do a check
to make sure that the user is entering a valid number; if the number is not valid, ask the user to
re‐enter it.
This is the proposed solution:
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
var timesTable;
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
}
if (timesTable == -1) {
break;
}
document.write("<br />The " + timesTable +
" times table<br />");
writeTimesTable(timesTable, 1, 12);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
</script>
</body>
</html>
This is my code, which also runs with the same result, without != -1:
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
var timesTable;
while (timesTable = prompt("Enter the times table", -1)) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
}
if (timesTable == -1) {
break;
}
document.write("<br />The " + timesTable +
" times table<br />");
writeTimesTable(timesTable, 1, 15);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
</script>
</body>
</html>
Why do I need != -1 parameter in the first while statement, since my code runs perfectly fine? Why is it there, what is it for?
The check for -1 is almost but not quite superfluous. It catches the conditions 'user canceled prompt' and 'user entered an empty string' which evaluates to false. In your version, this terminates the loop but the requirement is to terminate at user input '-1'.
If a while loop doesn't return anything, it will return as -1 (or false). In the case of the original example, I assume that the != -1 condition is there for example purposes only so it makes more sense to a beginner.
Let's say you were only wanting to terminate the while loop when the user entered -2. To do that, you would need to specify the != -2 condition in the loop, but -1 would still terminate the loop.
You're telling the browser/compiler to keep executing the code in the while loop until the user enters -1. When timesTable gets the value "-1" - that is, when the user enters "-1" - the while loop stops running.
// timesTable gets what the user enters in the prompt
// while timesTable is not equal to -1, execute the code in brackets
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);

Random number generator and if then statements

This code is supposed prompt for two player names and generate a random number between 1 and 6 for each player. It is then supposed to compare those two numbers and provide the output of which player has the higher number or display tie if there is a tie. Sometimes this works and sometimes it does the opposite other times it says both numbers match when they don't.
Anyone have any ideas for me?
var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "
main()
function main()
{
do {
getNames()
rollDice()
displayResults()
endProgram()
}
while (end == "yes")
}
function getNames()
{
playerOne = prompt("Please enter the name of Player One: ")
playerTwo = prompt("Please enter the name of Player Two: ")
}
function rollDice()
{
p1Number = Math.floor((Math.random()*6)+1)
p2Number = Math.floor((Math.random()*6)+1)
if (p1Number > p2Number)
{
return playerOne
}
else if (p1Number < p2Number)
{
return playerTwo
}
else
{
return "Sorry no winner, there was a tie"
}
}
function displayResults()
{
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
window.alert("The winner is! " + rollDice())
}
function endProgram()
{
end = prompt("Do you want to play again? Enter yes or no")
if (end == "no")
window.alert("Thank you for playing");
else if (end == "yes")
return end;
}
window.alert("The winner is! " + rollDice())
This line calls rollDice again for a 2nd time. You display the results of the first call then you re-roll and display the return value of the 2nd call (which may be different).
// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
// recall rollDice
window.alert("The winner is! " + rollDice())
In displayResults(), you are showing the values of p1Number and p2Number before assigning values to them (since that happens within rollDice()).
So your program is working, but your diagnostic output is misleading you.

Error when calling JavaScript function — "can't find variable"

I'm attempting to complete and exercise from the JavaScript Bible, and am having trouble getting my script to function.
The assignment is to create a page that allows users to query a planet's name, and, via a script that matches the planet's name with its data stored in the associate arrays, call up its distance and diameter information.
I'm attempting to call the function 'getPlanetInfo' via a button (onclick='getPlanetInfo()'). However, my error console reports that it cannot find a variable named 'getPlanetInfo' when I attempt to run it.
I've attached both my JS and HTML code below. Any idea as to why my function isn't being properly called would be hugely appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="planets.js"></script>
</head>
<body>
<h1>Check a planet's distance from the sun and its diameter!</h1>
<form>
<input type="text" name="entry" id="entry">
<input type="button" value="Check it!" onClick="getPlanetInfo()">
</form>
</body>
</html>
JS:
var planetNames = new Array(4);
planetNames[0] = "Mercury";
planetNames[1] = "Venus";
planetNames[2] = "Earth";
planetNames[3] = "Mars";
var planetDistances = new Array(4);
planetDistances[0] = "36 million miles";
planetDistances[1] = "67 million miles";
planetDistances[2] = "93 million miles";
planetDistances[3] = "141 million miles";
var planetDiameters = new Array(4);
planetDiameters[0] = "3,100 miles";
planetDiameters[1] = "7,700 miles";
planetDiameters[2] = "7,920 miles";
planetDiameters[3] = "4,200 miles";
function getPlanetInfo()
{
var selectedPlanet = document.getElementById("entry").value;
for (var i = 0; i < planetNames.length; i++)
{
if (planetNames[i] == selectedPlanet)
{
break;
}
}
if (i < planetNames.length)
{
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
}
else
{
alert("Sorry, " + selectedPlanet + " isn't in the database.");
}
}
This line:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
is missing a + sign after planetDistances[i], so the function has a syntax error and is not created, and naturally it's not found when called.
http://www.jsfiddle.net helps you create a reproducible case that we can all see, use it when you need to ask js questions.
You're missing a + - this:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
should be
alert(selectedPlanet + " is " + planetDistances[i] + " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
You should use something like Firebug to catch syntax errors when loading your script.

Categories