I am writing a simple program for school and running into trouble with an issue I am hoping someone could help me with
These are the assignment parameters:
Create a small JavaScript program that:
Creates a variable 'total' with a value of 0.
Use a do-while loop & function to prompt the user to enter a series of numbers, or the word "quit" - the quit command should be case insensitive.
If the user enters a number, add the new number to a running total.
If the user enters the word "quit" the loop should stop execution.
If the user enters a word other than quit the prompt message should change to let the user know they entered an invalid data type
When the loop is exited, display a message giving the total of the numbers entered
My code achieves all assignment parameters except I can't figure out how to get the prompt to disappear after the quit command is entered. The result still displays on the screen but the prompt keeps looping.
Here is my code:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
You are calling the askForNum function from inside itself (recursion), in effect starting a new do-while loop inside the previous one every time you type anything other than "quit".
Related
We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;
So the problem I am having is that whenever I try to make the to.Fixed(2); at the end of my g_fTotal I get a lint error and it also doesn't show up in the txtTotal field. IT shows up in the filed when I take the toFixed off but I need to have the total show only two decimal points. What am I doing wrong here?
// DO IT: Assign the total to the txtTotal textbox. Include a dollar sign and use .toFixed() to display 2 decimal places
document.getElementById("txtTotal").value = "$" + g_fTotal.toFixed(2);
This is the whole code below.
// DO NOT DELETE ANYTHING IN THIS FILE
/*jsl:option explicit*/
/*jsl:declare $*//*jsl:declare addEventListener*//*jsl:declare isDigits*//*jsl:declare alert*//*jsl:declare blur*//*jsl:declare clearInterval*//*jsl:declare clearTimeout*//*jsl:declare close*//*jsl:declare closed*//*jsl:declare confirm*//*jsl:declare console*//*jsl:declare Debug*//*jsl:declare defaultStatus*//*jsl:declare document*//*jsl:declare event*//*jsl:declare focus*//*jsl:declare frames*//*jsl:declare getComputedStyle*//*jsl:declare history*//*jsl:declare Image*//*jsl:declare length*//*jsl:declare location*//*jsl:declare moveBy*//*jsl:declare moveTo*//*jsl:declare navigator*//*jsl:declare open*//*jsl:declare opener*//*jsl:declare opera*//*jsl:declare Option*//*jsl:declare parent*//*jsl:declare Number*//*jsl:declare parseInt*//*jsl:declare print*//*jsl:declare prompt*//*jsl:declare resizeBy*//*jsl:declare resizeTo*//*jsl:declare screen*//*jsl:declare scroll*//*jsl:declare scrollBy*//*jsl:declare scrollTo*//*jsl:declare setInterval*//*jsl:declare setTimeout*//*jsl:declare status*//*jsl:declare top*//*jsl:declare window*//*jsl:declare XMLHttpRequest*/
// Constants (Constants are variables that never change throughout the running of your program. They are almost always declared globally.)
var gc_fSandwichPrice = 5.99; // Price for each sandwich (Version 1 and 2 only)
var gc_fExtrasPrice = 1.50; // Price for each extra item
// GLOBAL VARS
// Global object vars
var g_divErrors;
var g_radSandwich;
var g_radSize;
var g_chkExtras;
// Other global vars
var g_fTotal;
var g_sSandwich;
var g_sSize;
var g_sExtras;
// DO IT: Hook up an event handler for window.onload to the Init function.
window.onload = Init;
function Init() {
// DO IT: Change the version number in the line below, if necessary, so it accurately reflects this particular version of Dirty Deli.
document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0";
// DO IT: grab and assign any html objects you need to work with
g_divErrors = document.getElementById("divErrors");
g_radSandwich = document.getElementsByName("radSandwich");
g_radSize = document.getElementsByName("radSize");
g_chkExtras = document.getElementsByName("chkExtras");
// DO IT: Set the innerHTML of spanExtrasPrice to gc_fExtrasPrice. Tip: Use the .toFixed() method to display it with 2 decimal places
document.getElementById("spanExtrasPrice").innerHTML = gc_fExtrasPrice.toFixed(2);
// DO IT: Hook up any event handlers you need
document.getElementById("btnCalculateTotal").onclick = CalculateTotal;
document.getElementById("btnProcessOrder").onclick = ProcessOrder;
// Version 2
// DO IT: You need to hook up an event handler that runs whenever the user selects a different Payment option.
//This is the "onchange" event. I suggest you use an anonymous function, and make use of the *selectedIndex* property to see if they chose the credit card.
//This function will check to see if the user selected the Credit card option. If they did, set the CSS visibility property to "visible", otherwise set it to "hidden".
document.getElementById("selPayment").onchange =
function() {
var divCreditCardInfo = document.getElementById ("divCreditCardInfo");
if (document.getElementById("selPayment").selectedIndex === 2) {
divCreditCardInfo.style.visibility = "visible";
}
else {
divCreditCardInfo.style.visibility = "hidden";
}
};
} // function Init()
// function Init
function CalculateTotal() {
// this function should be called when the user clicks the Calculate Total button. Its purpose is mainly to, well, calculate the total. Remember to hook up an appropriate event handler so this function will be called when they click.
// DO IT: clear out divErrors (set the innerHTML to an empty string)
g_divErrors.innerHTML = "";
// DO IT: Tip: you're going to be adding to g_fTotal. Remember: adding anything to garbage will always give you garbage. So how do you prevent this error?
// Same deal for g_sExtras.
g_fTotal = 0;
g_sExtras = " ";
/* DO IT:
Sandwich code - Version 1
Using an IF statement, see which radio button they checked, and assign the value of the selected sandwich to a global var name g_sSandwich.
If nothing is selected, set divErrors to "Select a sandwich", and exit the function.
Sandwich code - Version 2
Within each IF statement remove the line of code you wrote for Version 1.
Replace it with a call to a function (that you will write) named GetSandwichName().
When you call this function, pass it one parameter - the index of the radSandwich radio button that the user checked.
More info on the function itself is given below.
*/
/* if (g_radSandwich[0].checked === true) {
GetSandwichName(0);
}
else if (g_radSandwich[1].checked === true) {
GetSandwichName(1);
}
else if (g_radSandwich[2].checked === true) {
GetSandwichName(2);
}
else if (g_radSandwich[3].checked === true) {
GetSandwichName(3);
}
else {
g_divErrors.innerHTML = "Select a sandwich";
return;
}
*/
// Version 3
/* CONVERT: Sandwich code
Using a FOR loop and a single IF statement within the loop, see which radio button they checked.
When you find it, set g_sSandwich to the sandwich name
and break out of the loop using the break command.
If nothing is selected, set divErrors to "Select a sandwich", and exit the function.
But how do you know if nothing was selected? Use a boolean variable in the If statement,
then check its value after you get out of the loop.
Remember: Your code should be flexible enough so that if the number
of sandwiches change, your code can still work.
Afterall, that's one of the reasons we're using a loop.
Do NOT call the GetSandwichName() function. Incorporate its code here, and remove it.
*/
var iChecked = false;
var i;
for (i = 0; i < g_radSandwich.length; i++) {
if (g_radSandwich[i].checked) {
iChecked = true;
g_sSandwich = g_radSandwich[i].value;
break;
}
}
if (iChecked === false) {
g_divErrors.innerHTML = "Select a sandwich";
return;
}
// Version 1
/* DO IT:
This is the Size code.
Make sure they selected a size.
Update the total by adding the price of a sandwich (which is already declared as a constant) to the total
If nothing is selected, set divErrors to "Please choose a size", and exit the function.
Tip: An If Statement is the key here.
*/
// Version 2
/*
In this version, the sandwiches are not all the same price.
The price of each sandwich is contained within the title attribute of the radSandwich radio button for that sandwich
(take a look at the html to verify this).
So, modify the IF statement from Version 1. You need to call a function (that you will write) named GetSizeUpdateTotal(). More on that below.
*/
/*
if (g_radSize[0].checked === true) {
GetSizeUpdateTotal(0);
}
else if (g_radSize[1].checked === true) {
GetSizeUpdateTotal(1);
}
else if (g_radSize[2].checked === true) {
GetSizeUpdateTotal(2);
}
else {
g_divErrors.innerHTML = "Please choose a size";
return;
}
*/
// Version 3
/* CONVERT: Size code
Once again, using a FOR loop and a single IF statement within the loop,
see which radio button they checked, get the price and update the total just like you did previously.
Then break out of the loop using the break command.
If nothing is selected, set divErrors to "Please choose a size", and exit the function.
Do NOT call the GetSizeUpdateTotal() function. Incorporate its code here, and remove it.
*/
iChecked = false;
var price;
for (i = 0; i < g_radSize.length; i++) {
if (g_radSize[i].checked) {
iChecked = true;
price = g_radSize[i].title;
price = price.substr(1);
price += Number(price);
g_sSize = g_radSize[i].value;
g_fTotal += price;
break;
}
}
if (iChecked === false) {
g_divErrors.innerHTML = "Please choose a size";
return;
}
/* DO IT:
"Extras" code - Version 1
Using an IF statement, see which extra(s) they checked. For each extra selected, do the following:
Concatenate the value of the selected extra to a global var name g_sExtras.
Update the Total with the price of the Extra.
"Extras" code - Version 2
Remove each IF statement you wrote for Version 1. Replace it with a call to a function (that you will write) named GetExtraUpdateTotal().
When you call this function, pass it one parameter - the index of the chkExtras checkbox that the user checked.
More info on the function itself is given below.
*/
GetExtraUpdateTotal(0);
GetExtraUpdateTotal(1);
GetExtraUpdateTotal(2)
// Version 3
/* CONVERT: "Extras" code
Again, using a FOR loop and a single IF statement within the loop, do what needs to be done. Remember NOT to break out of the loop when you find a checked checkbox (there may be more).
Do NOT call the GetExtraUpdateTotal() function. Incorporate its code here, and remove it.
*/
/* ****** That's it -- you're done with the loops. ******* */
// END Version 3
/* DO IT:
Optional fun: Remove the trailing comma on the last extra.
HINT: use the length property and the substr() method.
*/
// Version 1
// DO IT: Assign the total to the txtTotal textbox. Include a dollar sign and use .toFixed() to display 2 decimal places
document.getElementById("txtTotal").value = "$" + g_fTotal.toFixed(2);
} // function CalculateTotal
// Version 2
/* DO IT:
Declare function GetSandwichName().
This function takes one parameter, named p_iSandwichIndex,
which is a radSandwich radio button index, i.e. the index of the Sandwich they selected.
It assigns the value of the selected sandwich to a global var name g_sSandwich.
*/
// END Version 2
// Version 2
/* DO IT:
Declare function GetSizeUpdateTotal().
This function takes one parameter, named p_iSizeIndex, which is a radSize radio button index,
i.e. the index of the radSize radio button that they selected.
The function should assign the *value* of the selected size to a global var name g_sSize.
Also, it must update the Total with the price for the size they selected.
The price is located in the title attribute of the radio button (take a look).
Remember that (using dot notation) you can access any object attribute you want, once you grab the object.
But the price in the title attribute contains a dollar sign,
and you want everything AFTER the dollar sign.
Use the substr() method to get the entire string, starting with the SECOND character in the string.
Look back on our class notes to see how we did this.
Use an alert to see that you got what you intended.
Then, convert that string to a number and add it to the Total.
TIP: Declare local vars as necessary.
*/
// Version 2
/* DO IT:
Declare function GetExtraUpdateTotal().
This function takes one parameter, named p_iExtraIndex, which is a chkExtras checkbox index, i.e. the index of an extra they selected.
Use an if statement to see if this particular checkbox is checked. If it is, then do the following:
Concatenate the value of the selected extra to a global var name g_sExtras.
Update the Total with the price of the Extra.
*/
function GetExtraUpdateTotal(p_iExtraIndex) {
if (g_chkExtras[p_iExtraIndex].checked === true) {
g_sExtras += g_chkExtras[p_iExtraIndex].value + ", ";
g_fTotal += gc_fExtrasPrice;
}
}
function ProcessOrder() {
// This function should run when the ProcessOrder button is clicked.
// Version 2
// DO IT: declare any local vars you may need
var txtName = document.getElementById("txtName");
var txtMonth = document.getElementById("txtMonth");
var selPayment = document.getElementById("selPayment");
var selYear = document.getElementById("selYear");
var txtCreditCardNbr = document.getElementById("txtCreditCardNbr");
var month;
// Version 2
// DO IT: Before you do your error checking, does anything need to be initialized to an empty string? Now's the time to do it.
document.getElementById("divOrder").innerHTML = "";
g_divErrors.innerHTML = "";
// Version 2
// DO IT: If the name field is blank, display "Enter customer's name", set the focus and get out.
if (txtName.value === "") {
g_divErrors.innerHTML = "Enter customer's name";
txtName.focus();
return;
}
// Version 2
/* DO IT: Credit Card Code
Use an IF statement to determine if the user selected the credit card option in the selPayment dropdown
If they did, you need to do the following:
if the credit card number field was left blank or the contents of the field is not a number, display (in divErrors) the message shown in the working version, put focus on the card number field and get out.
if the month field was left blank or the contents of the field is not a number, display the message shown in the working version, put focus on the month field and get out.
if the month they entered is less than 1 or > 12, display the message shown in the working version, put focus on the month field and get out.
TIP: Remember to convert the txtMonth value to a number before you do your comparison.
if they neglected to select a year, display the message shown in the working version, put focus on the year field and get out.
*/
// END Version 2
// The following section I got assistance from another classmate.
if (selPayment.selectedIndex === 2) {
if ((txtCreditCardNbr.value === "") || (isDigits(txtCreditCardNbr.value) === false)) {
g_divErrors.innerHTML = "Enter your card number using only digits";
txtCreditCardNbr.focus();
return;
} else if ((txtMonth.value === "") || (isDigits(txtMonth.value) === false)) {
g_divErrors.innerHTML = "Enter month using only digits";
txtMonth.focus();
return;
} else {
month = Number(txtMonth.value);
if ((month < 1) || (month > 12)) {
g_divErrors.innerHTML = "Enter month between 1 and 12";
txtMonth.focus();
return;
}
}
if (selYear.selectedIndex === 0) {
g_divErrors.innerHTML = "Please select a year";
selYear.focus();
return;
}
}
// DO IT: Concatenate the appropriate msg into divOrder. The Welcome msg is within an h3 tag. Every other line is within a p tag. The last line is in bold.
/* Version 1:
Do not include the user's name in the welcome message.
Do not include the "Paid by" statement.
*/
/* Version 2:
Include the user's name in the welcome message.
Include the "Paid by" statement.
*/
document.getElementById("divOrder").innerHTML =
"<h3>Welcome to Dirty Deli!</h3>" + txtName.value + "<br>" +
"You have ordered a " + g_sSize + " " + g_sSandwich + " with " + g_sExtras + "<br>" +
"Your total is " + document.getElementById("txtTotal").value + "<br>" +
"Paid with " + selPayment.value + "<br>" + "<br>" +
"<strong>Have a nice day!</strong>";
} // function ProcessOrder
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be many ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
Not only did you confuse yourself, but you crashed the browser! :-)
(The for loop never terminates because you push a new value to the list on every iteration.)
I could tell you what's wrong with the code in more detail, but you'll learn a lot more if you chase it down yourself. So what you need now is to learn the art of debugging.
Add a debugger statement at the beginning of your test() function:
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
debugger;
var info = prompt("hi " + input + " what is your name?");
for(i=0; i< list.length; i++){
if( info === list.length[i]){
console.log(list[i]);
}
else{
list.push(info);
}
console.log(list);
}
}
Now run test() and it will stop in the debugger at that statement. Look at the different panels in the debugger - you can view your variables and other stuff. Find the place where it has controls to let you step through your code. Single-step through the code and look at the variables as you go. You will soon discover what the problems are. In most browsers there are also keyboard shortcuts to let you step through the code more easily.
If you use Chrome, here is an introduction to the Chrome DevTools. There are similar tutorials for the other browsers too.
heres an algorithm :
Use an object to store the user no. and the count. like :
{"222":"3","444":"1"}
this means 222 has visited 3 times and 444 visited once. now every time a user checks in:
see if the key with the user's number exists, if yes increment the count. if no, add a new entry with count = 1.
check if the number is 5, if yes get free coffee and reset count to zero. skip if no.
I would solve the problem by storing the visit count in a dictionary that maps each customer's ID to the number of times they have visited. The dictionary is initially empty. When you look up an ID in the dictionary for the first time, you'll get undefined, which tells you that you must initialize the value.
The following demonstration has a couple of buttons that you can use to make Alice or Bob visit the shop. Click on the blue button at the bottom to start the demo.
function message(s) { // Simple output for a code snippet.
document.getElementById('display').innerHTML += s + '<br />';
}
var coffeeCount = {}; // Stores the number of visits by each customer.
function customerVisit(id) { // Called when a customer visits.
if (coffeeCount[id] === undefined) { // Check for first visit.
coffeeCount[id] = 0; // Initialize the visit count.
}
var count = ++coffeeCount[id]; // Increment the visit count.
message(id+': '+count+' visit'+(count == 1 ? '' : 's'));
if (count % 5 == 0) { // Check for free coffee.
message('→ Free coffee for customer '+id+'!');
}
}
<button onclick="customerVisit('Alice')">Alice</button>
<button onclick="customerVisit('Bob')">Bob</button>
<div id="display"></div>
Try including utilization of input elements; set visits count as value of property id, info at object list; call test with value of input element : id ; or at prompt : info . At five visits , display coffee , reset value of id to 0.
var list = {
"111": 0,
"222": 0,
"333": 0,
"444": 0,
"555": 0,
"666": 0
};
var test = function test(id) {
coffee.innerHTML = "";
var info;
if (id.length > 0 && !/^(\s)/.test(id)) {
if (list.hasOwnProperty(id)) {
++list[id];
} else {
list[id] = 1;
}
info = confirm("hi " + id + " this is your " + list[id] + " visit");
} else {
info = prompt("hi, please enter an id");
if (!!info && !/^(\s)/.test(info) && list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
} else {
info = prompt("hi, please input a different id");
if (!!info && !/^(\s)/.test(info) && !list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
}
};
alert("please try a different id")
};
for (var id in list) {
if (list[id] === 5) {
alert("hi " + id + ", thanks for visting " + list[id] + " times");
coffee.innerText = "☕";
list[id] = 0;
break;
}
};
console.log(list);
};
var inputs = document.querySelectorAll("input");
var coffee = document.getElementById("coffee");
coffee.style.fontSize = "5em";
inputs[1].onclick = function(e) {
test(inputs[0].value)
};
<input type="text" placeholder="please enter id" value="" />
<input type="button" value="click" />
<div id="coffee"></div>
n is number of costumer
Initially array is [0,0,0,.....n times]
All values are 0 because no costumer has visited the shop.
For n=5 array would look like
var a=[0,0,0,0,0];
1)To solve this problem in array.
2)Suppose we have array of size n.
3)then index of the array will be 0...n-1
4)So we can map id of costumer to the index.
5)And value will keep count of the number of visit for the index.
6)a[5]=11; here 5 is index and 11 is value
7)For our problem if customer with id i we increment a[i]=a[i]+1 if he visits .
8) Then we can check
if(a[i]+1 === 5) {
console.log("Custumer "+ i + " get a free coffee");
a[i]=0;
}
else {
a[i]=a[i]+1;
}
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be manyt ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
I will give you a short function to check how many times a specific value is at the array:
function countHowManyTimesAValueIsOnArray(arr, valueToCheck){
return arr.filter(function(arrayValueToCompare){
return arrayValueToCompare === valueToCheck;
}).length
}
Attention for the use of '===' instead of '=='. This will compare the value considering its type. 222 will not be found as "222"
No need to complicate things here's an simple way, just add a count function that search how many times user has enter
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
var info = prompt("hi " + input + " what is your name?");
var check=0;
for(i=0; i< list.length; i++){
if( info === list[i]){
check=1;
break;
}
}
list.push(info);
if(check==1){
count(info);
}
}
function count(info){
var count=0;
for(i=0; i< list.length; i++){
if(list[i]===info)
count++;
}
console.log(count);
}
}
I found a similar question for this same assignment but that person was using a different type of loops. I have been struggling with this assignment and even with the teacher giving me pseudo code to try to explain it further I am still having difficulties with it writing out what it's supposed to in the end.
We are supposed to create an array that holds the price of theater tickets, then make a html table that has the different level of tickets and prices that correspond with the numbers in the array. After this we prompt the user for their name and validate that they did enter something. Then we are supposed to create a function named numSeats that prompts the user for the number of
seats that they want to buy and validate that they entered a number and the maximum number of seats they can buy in one transaction is 6.
We are supposed to use a loop to
prompt the user until they enter a valid number, then create a function named seatingChoice that prompts the user for where they would like the seats to be by indicating the correct number from the table.
seartingChoice also needs to validate that they entered a number 1-4 and use a loop to prompt the user until they enter a valid number. If the user at any time hits the cancel button in a prompt we are supposed to give an alert of "Sorry you changed your mind". This is missing from my code because i haven't figured out how to do that.
When the program calculates everything and writes to the screen in the end it is supposed to write like "UsersName ordered #tickets for a total of dollaramt" but instead it writes "Null ordered null tickets for a total of $null." The following is what i have the the javascript part of the code:
var Prices = [60, 50, 40, 30];
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
function numSeats () {
var seats = prompt("Please enter the number of seats you want to buy");
parseInt(seats);
while((seats = null)||(seats > 6))
{
seats = prompt("Please enter a number between 1 and 6");
parseInt(seats);
}
return seats;
}
var seatswanted = numSeats ();
function seatingChoice () {
var choice = prompt("Please enter where you would like your seats to be located by indicating the correct number from the table");
parseInt(choice)
while((choice = null)||(choice > 4))
{
choice = prompt("Please enter a number between 1 and 4, corresponding to your section choice");
parseInt(choice);
}
return choice;
}
var seating = seatingChoice();
var dollaramt = (seatswanted * Prices[seating-1]);
document.write(Usersname + " ordered " + seatswanted + "tickets for a total of " + "$" + dollaramt + ".");
Instead of comparison operator you are using assignment operator:
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
and prompt return empty string if user wont input anything so instead of null compare it to empty string i.e, ''. so change this to:
var userName = prompt("Please enter your name");
while(userName == '')
{
userName = prompt("Please enter your name");
}
There are several errors in your code. You can try your code using jsfiddle (you can try your code properly modified here: http://jsfiddle.net/pu3s0n50/).
Your errors are that you assign Username, seats and choice instead of comparing them, i.e.:
while(Usersname = null)
should be
while(Usersname == null)
and
while((seats = null)||(seats > 6))
should be
while((seats == null)||(seats > 6))
and finally
while((choice = null)||(choice > 4))
should be
while((choice == null)||(choice > 4))
The error I do not know why this happening, but this maybe solve your issue.
var Usersname = '';
Usersname = prompt('Choose a Username:');
this works. And you need the same for the others prompt.
Also if you want seat in rang 1-6: while((seats = null)||(seats > 6)) its wrong. Change to ((seats <= 6) && (seats > 0))
Maybe this could help you.
Best regards.
I'm making a small web program that takes in words and tells you them back alphabetically or if numbers, numerically. I believe everything is working except showing the words after gathering the input. I try to write the words to the page but they don't show up because I believe you have to update the page somehow which I have no idea on how to do so.
My JavaScript code:
var input = null;
var words = new Array();
alert("Enter one word at a time in the next prompts. Enter passw0rd to finish/stop.");
do {
input = prompt("Enter word...enter passw0rd to exit.");
if ( input != "passw0rd" ){
words.push(input);
}
else{
break;
}
}while( input != "passw0rd" );
words.sort();
alert("Your words alphabetically are...");
for ( var i = 0; i < newList.length; i++ )
{
document.writeln(words[i]);
}
It looks like your for loop is using newList, when it should be using words.