Im having problems finishing the codeavengers practice tutorial
when i run this code it just crashes, any idea why?
The purpose is to count how many teenagers from the range of 13-19
var age1 = prompt('Please insert your age');
var age2 = prompt('Please insert your age');
var count = 0;
if (age1 > 12 && age1 < 20 || age2 > 12 && age2 < 20) {
count = count + 1;
}
alert(count);
there is nothing that will stop the while loop! age1 and age2 are static values that are never changing. Also don't forget the semicolins on lines 1 and 2
Related
I am really new in coding therefore I am coding currently a Taximeter. Unfortunately is the result of my code when executing NaN in the console. I tried some ways to rectify my problem but those attempts did not work. I think that some variables are not in the right scope but I do not know how to fix that.
function Taximeter() {
const y = 3.9;
const km = prompt("How far is your target");
if (km <= 7) {
var routePrice = 2.3;
} else if (km > 7) {
let routePrice = 1.65;
var subtractedLength = (km -= 7);
var partialExpenses = (subtractedLength *= routePrice);
var tosevenExpenses = 7 * 2.3;
var combinedExpenses = (tosevenExpenses += partialExpenses);
}
const persons = prompt("How much persons are driving with you?");
if (persons > 8) {
console.log("Only 8 persons can drive with you.");
} else if (8 >= persons >= 5) {
var personsExpenses = 5;
} else if (0 >= persons >= 4) {
personExpenses = 0;
}
if (km <= 7) {
var wholeExpenses = y + km * routePrice + personsExpenses;
} else {
var wholeExpenses = combinedExpenses + y + personsExpenses;
}
console.log(wholeExpenses);
}
It would be helpful to know where exactly NaN is coming up and whether or not you are seeing NaN as the result of an Exception (if an error message was logged to the console) or if NaN is coming up as a result of your own console.log() statements. Part of the issue could be that the function prompt() returns a String, meaning that your variable km is going to be a String and not a Number. Use this line of code instead and it might fix your problem:
const km = parseInt(prompt("How far is your target"));
EDIT:
In response to your comment, there are a couple other issues I see here. There is the issue with your first if and else if clauses where the indentation is a little off. This, as far as I can tell, should not actually affect your code, but it does make it harder to read. Here is how it should look:
if (km <= 7) {
var routePrice = 2.3;
} else if (km > 7) {
let routePrice = 1.65
var subtractedLength = km -= 7;
var partialExpenses = subtractedLength *= routePrice ;
var tosevenExpenses = 7 *2.3;
var combinedExpenses = tosevenExpenses += partialExpenses;
};
Second, in those same if and else if clauses, you use the -=, *=, and += operators when they are unnecessary and may cause errors. I've never seen them used the way that you have before, so I don't know if they actually cause errors, but I would edit those clauses one more time for readability at least:
if (km <= 7) {
var routePrice = 2.3;
} else if (km > 7) {
let routePrice = 1.65
var subtractedLength = km - 7;
var partialExpenses = subtractedLength * routePrice ;
var tosevenExpenses = 7 *2.3;
var combinedExpenses = tosevenExpenses + partialExpenses;
};
Like with km I would also edit your persons declaration to turn that variable into a Number so that the logic operators that you use on it later work properly:
const persons = parseInt(prompt("How much persons are driving with you?"));
Another thing, like a commenter earlier pointed out, 8 >= persons >= 5 will not work the way you think it will - just edit those if and else if clauses like so to fix that error:
if (persons > 8) {
console.log("Only 8 persons can drive with you.");
} else if(persons >= 5 && persons <= 8) {
var personsExpenses = 5;
} else if (persons <= 4 && persons >= 0) {
personExpenses = 0;
};
Finally, your variable declaration of personsExpenses is such that the variable will only be declared if that first else if clause resolves. You need personsExpenses to be declared no matter what, so I would declare it before and outside of any of those conditional clauses:
var personsExpenses
if (persons > 8) {
console.log("Only 8 persons can drive with you.");
} else if(persons >= 5 && persons <= 8) {
personsExpenses = 5;
} else if (persons <= 4 && persons >= 0) {
personExpenses = 0;
};
That's everything that I noticed, so good luck!
I have been asked to make a prompt to enter your current weight and target weight. The loop should calculate how many weeks it will take to reach target weight at loss of 1.38 a week. My prompts work but the loop breaks the javascript. My code is below, can someone help me out? I am new to javscript by the way.
var current_weight = prompt("Please enter your current weight",0.0);
var target_weight = prompt("Please enter your target weight",0.0);
var weeks = 0;
if(current_weight > 0 target_weight > 0){
if(current_weight > target_weight){
while(current_weight <= target weight){
var current_weight = current_weight – 1.38;
weeks = weeks + 1;
alert("it will take" + weeks + "weeks to hit target");
}
}
else if(current_weight > 0 && target_weight > 1){
alert("Current weight must be more than target weight");
}
else{
alert("Input error")
}
</script>
The loop breaks the javascript.
4 problems in your code:
missing && operator between the conditions in first if statement
prompt returns the user entered value as string. So you can't subtract 1.38 from current_weight as current_weight will be a string. You need to convert user entered values in to numbers
There's a logical error in your code. You have this if statement if(current_weight > target_weight) and if it evaluates to true, then while loop checks while(current_weight <= target weight) which is opposite to the condition of the wrapping if statement. Consequently, your loop will never run. You probably want loop condition to be current_weight > target_weight
alert should be outside the while loop
var current_weight = Number(prompt("Please enter your current weight", 0.0));
var target_weight = Number(prompt("Please enter your target weight", 0.0));
var weeks = 0;
if (current_weight > 0 && target_weight > 0) {
if (current_weight > target_weight) {
while (current_weight > target_weight) {
current_weight = current_weight - 1.38;
weeks = weeks + 1;
}
alert("it will take" + weeks + "weeks to hit target");
} else if (current_weight > 0 && target_weight > 1) {
alert("Current weight must be more than target weight");
} else {
alert("Input error");
}
}
I want to check fields "Code1 to Code 32" for anything starting with "A" and ending with "B". I want the count to output to the field "Total1". I input the code under properties of "Total1" in the custom calculation. The Javascript doesn't calculate. What am I doing wrong?
var total = 0;
for (var i = 1; i <= 32; i++) {
var f = this.getField("Code" + i).valueAsString;
var v = f.valueAsString;
if (v.charAt(0) == "A" && v.charAt(v.length - 1) == "B") total++;
}
event.value = total;
I'm making trying to push data into an object, but as soon as I push data to userID.name, the value of userID.age gets reset(?) in the console. Here's my code:
if (input.indexOf("ben") >= 0){
var slot = splitInput.indexOf("ben");
console.log(slot)
i = slot + 1;
if (splitInput[i].indexOf(0) >= 0 || splitInput[i].indexOf(1) >= 0 || splitInput[i].indexOf(3) >= 0 || splitInput[i].indexOf(4) >= 0 || splitInput[i].indexOf(4) >= 0 || splitInput[i].indexOf(5) >= 0 || splitInput[i].indexOf(6) >= 0 || splitInput[i].indexOf(7) >= 0 || splitInput[i].indexOf(8) >= 0 || splitInput[i].indexOf(9) >= 0){
i = 0;
var slot = splitInput.indexOf("ben");
// console.log(slot)
i = slot + 1;
userID.age = splitInput[i];
console.log(userID);
} if (splitInput[i].indexOf("a") >= 0 || splitInput[i].indexOf("e") >= 0 || splitInput[i].indexOf("i") >= 0 || splitInput[i].indexOf("u") >= 0){
i = 0;
var slot = splitInput.indexOf("ben");
// console.log(slot)
i = slot + 1;
userID.name = splitInput[i];
console.log(userID);
}
}
Here's my splitInput:
var splitInput = input.split(" ");
input is gathered through a getElementById function.
When I manually log userID I get this error VM935:1 Uncaught ReferenceError: userID is not defined(…) which may have something to do with it, although console.log(userID) works fine.
If you need more information, please let me know.
Thanks in advance!
Before assigning to an object property, like UserID.age, you must first have defined UserID itself.
So put this before you access a property of UserID:
var userID = {};
Remarks on the code
The way you check for numbers and words with vowels is not really that nice. It has a lot of repetitive code. Also inside the if blocks you were searching again for the word "ben", while you had that already done... Seems unnecessary to do that again.
Have a look at this version of your code:
// Sample data
var input = 'ik ben 51 jaar';
var splitInput = input.split(" ");
// This was missing:
var userID = {};
// Move retrieval of slot before the `if` so it can be reused
var slot = splitInput.indexOf("ben");
if (slot >= 0){
console.log('slot:', slot);
i = slot + 1;
// Make sure you are not at the end of the array, and
// use a regular expression to see next word consists of digits only
if (i < splitInput.length && splitInput[i].match(/^\d+$/)){
// convert the word to number with unitary plus:
userID.age = +splitInput[i];
}
// You'll maybe want to do an else here.
// Use regular expression again; don't forget the "o"
else if (i < splitInput.length && splitInput[i].match(/a|e|i|o|u/)){
userID.name = splitInput[i];
}
console.log(userID);
}
I have been struggling to get my head around this for a while now.
I am attempting to create a countdown timer. Eventually I want it to reset after every 5 hours starting from 8am. But for now I can't figure out if im setting the hours, minutes and seconds correctly to count down together properly.
This is my code so far:
<?php
$timeTo = strtotime('08:00:00').'<br />';
$timeNow = strtotime('now').'<br />';
$differenceInSeconds = $timeTo - $timeNow;
?>
<script type="text/javascript">
var s= "<?php Print($differenceInSeconds);?>";
var h= Math.floor(s/3600);
s-= h*3600;
var m= Math.floor(s/60);
s -= m*60;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
s=s-1;
if(h >= 0 && m >= 0 && s <= -1){
m=m-1;
s=59;
if(h>= 0 && m < 0 && s <= -1){
h=h-1;
m=59;
s=59;
if (s <= -1)
{
//counter ended, reset counter
return;
}
}
}
//Do code for showing the number of seconds here
document.getElementById("timer").innerHTML=(h <= 0 ? ' ' : h+"hr ")+(m <= 0 ? ' ' : m+"min ")+(s < 10 ? '0'+s : s+"secs "); // watch for spelling
}
</script>
Am I barking up the wrong tree here? I am new to times and javascript so finding it difficult.
I will not answer this. I will just try to lead you to the answer.
Note that s <= -1 is logically equivalent to s < 0. There is no confusion about it. Use the second one, it looks more clean.
s=59; and in the next line how on earth will if(h>= 0 && m < 0 && s <= -1 ) ever evaluate to true ?
Similar other logical mistakes are present as well. Take some time and fix this. If you fix this on your own then you're one step closer to becoming a good programmer.
Happy Coding... :)