The code is:
function roundAmount(theDecimal) {
var s = "" + Math.round(theDecimal * 100) / 100
var i = s.indexOf('.')
if (i < 0) {
return s + ".00"
}
var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
if (i + 2 == s.length)
t += "0"
return t
}
The line with the error:
if (i < 0) return s + ".00"
The error is:
error: expected (;)
does anyone know how to fix this?
About your script:
The problem in the script above is that last if statement which does some operations followed by a return. You need a semi-colon after the operation.
In the future, as good practice, make sure to put a semi-colon after every valid statement. That way this won't bother you.
Think of each line as a thought, and curly braces as ways to "group" and "relate" thoughts together.
The below is a full thought that says "give me a variable "i" and give it the value 1 + 2;
var i = 1 + 2;
The below is a full thought about a condition that says "If i is 3 then add 1 to i". The thought "add 1 to i" is its own thought, so it needs a semicolon. Since the curlybraces for the IF statement are special in that they don't need a semi-colon after their "full thought" as long as you put a "block" (which is what curlybraces really make) after it, to enclose the thought.
This means the following is valid:
if( i == 3 ) {
i = i + 1;
}
The following is not valid because the semi-colon after the if ends the "thought" before the if knows what to do if i equals 3:
if( i == 3 ) ; {
i = i + 1;
}
For a basic JavaScript tutorial, check out W3Schools.
"There must be a better way?"
Any time you find yourself doing a lot of string operations on decmials, it's a good idea to ask yourself "is there a better way to do this?".
It looks like you're writing a function to round a number to the nearest hundredths while displaying two decimal points. There's a much easier way to do this. You can just round to the nearest hundredths and have javascript output the fixed point number.
Example:
function roundAmount( theDecimal ) {
//first round to the nearest hundredth
//then return the value with two decimal places as a string
return theDecimal.toFixed( 2 );
}
if (i < 0) return s + ".00";
Note the ; at the end of the statement. Personally, I prefer surrounding almost all my ifs in {} such as
if (i < 0)
{
return s + ".00";
}
Which helps in debugging and stepping though code.
It's expecting a semicolon, so add a semicolon.
if (i < 0)
return s + ".00";
Add a semicolon at the end of the line! Like this:
if (i < 0) return s + ".00";
I don't see anything particularly wrong with the code you posted in the earlier comments, but may I suggest always adding a semi-colon to the end of your statements. Though they are not required, it usually makes it easier to debug problems such as these.
Related
This question already has answers here:
if statement always return true even for simple integer values
(3 answers)
Closed 2 years ago.
I've been teaching myself how to code in new languages and might be asking a couple of silly questions here for a while.
Trying to put this to work but, when the output pops out and the grade I've typed into is higher than 50, it was supposed to show the word "PASS". Instead, I'm still getting "FAIL" - the amount doesn't matter.
I am pretty sure it has to do with the conditionals, but I've been stuck on this for a long time now.
Here is my code:
var input = Number(prompt("Enter a grade between 0 and 100.")); //enter grade
if (input > 100 || input < 0) {
alert("Grade not valid. Enter a grade between 0 and 100."); //validate grade
} else {
if (input < 50); //result FAIL
{
result = "Fail";
alert("FAIL");
}
/*
if (input > 50); //result PASS - This part doesn't work
{
result = "Pass";
alert("PASS");
}
*/
total = total + input;
entrys = entrys + 1; //show inputed grades
document.write("<br>" + "Grade " + entrys + " = " + input + " = " + input / 100 + "%" + " " + result); // Every inputed result is considered "Fail"
}
The semicolon after the if (input < 50) turns the if statement into a one line if with an empty expression, followed by a code block that always runs. You can fix your issue by getting rid of the semicolon.
if (input < 50); //result FAIL
// ^ this is bad
As others have already pointed out, you need to remove the ; from the line if you want the rest of the statements to execute. The reason why is because, traditionally, in compiler languages the semicolon(;) is used to mark the end of the line. In javascript, they are also used for that purpose, but they are optional in javascript.
So if your code spans multiple lines, avoid using it unnecessarily. Definitely don't use it after a for or while loop(unless for certain use cases where you want that), or after an if-else statement, because execution will get stopped at that line and the next line will be executed like it is an unrelated code and not part of the loop/statement. Hope this makes sense
I wrote this program out in plain code but I don't know Javascript well enough to get all the syntax right. I am a beginning programming please help me with corrections to my code. It is currently not running at all. We are still going over loops and it's really giving me trouble. This is for a college class. (I know this isn't formatted properly that's why i'm asking for help)
function main() {
alert("Welcome to the program");
var fatGrams = getFatGrams(fatGrams);
var calories = getCalories(fatGrams,calories);
var percentage = caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
Errors in your code :
The function keyword is not needed to call a function. Remove the keyword function before calling a function and simply call the function as getFatGrams(fatGrams);
You are not passing parameters to function caloriesPercentage. Change it to caloriesPercentage(fatGrams,calories);
The expression for a while loop should be enclosed in paranthesis as while(fatGrams < 0).
The OR should be written as ||.
Use + to concatenate 2 string (Or a string and a variable)
"The amount of calories that come from fat is, " + percentage
The expression for an while should also be enclosed in paranthesis as if(percentage < 0.3) and no then is needed. The curly brackets of if should be closed before else.
if(percentage < 0.3){
alert("The food is low in fat.");
}
else {
alert("The food is not too low in fat.");
}
assign value from prompt to variable as
fatGrams = prompt("Enter the new number of fat grams.");
Your final code should look like this :
function main() {
alert("Welcome to the program");
var fatGrams;
var calories;
var percentage;
getFatGrams(fatGrams);
getCalories(fatGrams,calories);
caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
welcome to the wonderful world of programming!
It looks like you are getting the basics down, let me explain some of the issues you are having with JavaScript. I'm going to use some big words (as will many other experienced developers so get used to them!).
Function Declaration vs Function Invocation
The very first issue I see with your main() function is a confusion about when to use the function keyword in JavaScript. You only need to use function when you are declaring a function, or in other words when you want to "create a new function." When you declare something, you are creating it, and in JavaScript the function keyword is how you declare (aka create) a Function. Here is an example of creating a "named function" in javascript.
function addTwo( number ) {
return number + 2;
}
That right there is a "named function" declaration. On a side note, you can also create functions as "expressions" (which would be called a "function expression"). That would look like this
var addThree = function( number ) {
return number + 3;
};
Note that in both cases we are creating a function with the function keyword.
When you want to use a function, you "invoke" it. This is also referred to as "calling" a function. To call (aka invoke) a function you simply write the function name with parenthesis behind it, passing in any arguments. Function invocation works the same for both named functions and function expressions. So we could invoke the two functions above like so
var four = addTwo( 2 );
var five = addThree( 2 );
Simply put, only use the function keyword to make functions. To call or use a function just put ( argument, otherArg ) at the end of the function name.
Branching Statements
The next thing I see is that you're missing some parenthesis! JavaScript has a C style syntax so that means you need to put parenthesis around expressions for if, else if, and switch statements. Those keywords I listed are what we call Branching Statements. They allow you to conditionally execute code based on some true or false value, as opposed to Looping Statements that allow you to repeat code based on a true or false value. The structure for an if .. else branching statement in JavaScript is as follows.
if ( number % 2 === 0 ) {
number *= 2;
} else if ( number % 3 === 0 ) {
number *= 3;
} else {
number += 5;
}
For both if and else if you need to provide an "expression" to branch around. An else statement is always executed if none of the if or else if expressions evaluated to true. The else clause is not required so if you don't have any code in your else block you can just remove it! It is perfectly fine to have a single if statement like this in your code
if ( needsCleanup ) {
doCleanup();
}
Of course it would be ok to have an else if clause and no else clause, the else is always optional. But remember the else clause never has an expression so you should never write () after a simple else.
Looping Statements
Looping is a big concept that takes a while to master so don't get frustrated or discouraged! In JavaScript we have for, while and do while loops. Just like if statements looping statements need an expression, but in this case they need it to know when to stop looping. I'm not going to cover do while loops because they are rarely used and can be confusing when just starting out. Simply put, looping statements say: "keep executing this code block until the expression is false." I find it easiest to illustrate this with a for loop. For loops are a great way to run a code block a specific number of times. Let's look at an example that adds all the numbers from 1 to 10 with a for loop.
var sum = 0;
for ( var i = 1 ; i <= 10 ; i++ ) {
sum += i;
}
// sum will be 55
// i will be 11
A for loop has three expression separated by ;. The first is for initialization and is only executed before the loop starts (the var i = 1 part). The second is the condition that is checked before each iteration. The last is an increment operation that is executed at the end of every loop execution. If we were to re-write this for loop as a while look it would look like this...
var sum = 0;
var i = 1;
while ( i <= 10 ) {
sum += i;
i++;
}
So you can see the var i = 1 happens before the loop starts. The i <= 10 happens before each time the loop runs its body (the part in the {}). And the i++ happens at the end of the loop before it checks i <= 10 to see if it should keep looping.
String Concatenation
String concatenation is the process of putting two strings together. In JavaScript the + operator does double duty as addition 1 + 1 and string concatenation 'hello' + ' world'. So when you want to put two strings together you simply add them! If the strings are in variables then you can just "add" them together...
var salutation = 'Hello';
var name = 'Kylie';
var greeting = salutation + ', ' + name;
// greeting will be "Hello, Kylie"
I hope that clears some things up, if you have any questions please let me know!
Because this IS for a class I am NOT going to give you the answers but instead point out the issues.
Calling a function in Javascript and return a value:
var myvalue = myFunction();
You have function... in your main and need to fix that.
Some functions just return values and thus calling them needs no parameter (like above) others need parameters for the inputs which you have done.
Prompt returns a value and you need to capture that value:
var myinputvalue = prompt("enter value");
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Conditionls need to be wrapped in parenthesis when using while, if etc.
while (mything < 0){ Reference; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
" OR " in a conditional is represented by || and an AND by &&
NOTE: You can use some on-line tools to work out some of the issues for example paste your code into http://jshint.com/ and it will tell you many of the syntax issues.
Hello I have some experience with javascript but I would really like to learn how to program in C and one of the ways I am trying to learn is by converting some simple javascript code into C. My current attempt at converting a simple program compiles without any errors however doesn`t produce the answer I want it to. The javscript code produces the correct answer and I wrote it to solve project euler problem number 5 which can be found here: https://projecteuler.net/problem=5
Here is the working js code:
var number = 2520;
var count = 1;
var solved = false;
while (!solved) {
if (number % count === 0) {
if (count === 20) {
solved = true;
console.log(number);
} else {
count++;
}
} else {
number++;
count = 1;
}
}
Here is the C conversion which does not work:
#include <stdio.h>
int main () {
unsigned int number = 2520;
unsigned int count = 1;
unsigned int solved = 0;
while ((solved = 0)) {
if (number % count == 0) {
if (count == 20) {
solved = 1;
printf("%number");
} else {
count++;
}
} else {
number++;
count = 1;
}
}
return 0;
}
while ((solved = 0)) {
You can use the same syntax you would use in js here, namely, while (!solved), or ==, but just = is an assignment.
printf("%number");
Doesn't mean what you think it means, which is why it's not an actual error (%n is a distinct specifier, and with no corresponding input, you'd get umber as the output). To reproduce console.log() you'd want:
printf("%d\n", (int)number);
Or
printf("%u\n", number);
Notice the explicit \n, since printf() does not add a newline otherwise.
Replace
while (solved = 0)
with
while (!solved)
and
print("%number")
with
print("%u\n",number)
I know its already answered, but you should know why.
while ((solved = 0))
Will actually set solved to 0 AND return 0 (which is interpreted as false). So the while loop is exited right away.
printf also takes a pretty strictly formatted string for the first one (just typeing what makes sense is guarenteed to be wrong). The compiler has know way to know what is inside the string is anything other than a string (C++ has (almost) NO reflection, unlike javascript: your written code dissapears into ones and zeros). printf needs to take number in as the second argument. Try printf("%i\n",number);. That says "Print an integer followed by a newline. The integer's value is number."
Welcome to C! Your biggest problem going into is is going to be my biggest problem with Java Script: C is strictly typed with no reflection, while javascript has no types with almost everything relying on some sort of reflection.
I have some code that is not passing lint. Is there is a better way to do this?
The first error is
lint warning: leading zeros make an octal number
function getNumberCounter(lastNumberString, simple){
var myCount;
if(!lastNumberString){
return "-1";
}
else{
switch(lastNumberString.split("-")[1]){
case "08" : myCount = 9;
break;
case "09" : myCount = 10;
break;
case "99" : myCount = 00;
break;
default : myCount = parseInt((lastNumberString.split("-")[1]),10) + 1;
break;
}
if(!simple){
if(myCount <= 9){
return ('0' + myCount);
}
}
return myCount;
}
}
and the other one is
lint warning: increment (++) and decrement (--) operators used as part of greater statement
function getRandomString(_length){
_retString = "";
_charSet = "0123456789abcdefghijklmnopqrstuvwxyz";
while(_length--){
_retString += _charSet.charAt(Random(0, _charSet.length-1));
Delay(1);
}
return _retString;
}
also this is javascript but it is not html type does anyone know what type it is, tried to use a javascript checker and it wants me to write html based code.
why is this happening and does it have an actual impact on the software I am using on my computer.
In many languages, a number with a leading zero is considered to be a octal (i.e. base 8) literal, apart from 0 itself. For example 012 is the decimal number ten, even though it looks more like twelve. So 00 is considered to be an octal number, although it's obviously zero.
Octal literals are however a syntax error in strict mode, as octal numbers were never part of the ECMAScript standard. I imagine your linter is enforcing the same rule.
So the fix to your first problem is simple:
case "99" : myCount = 0; // Drop one of the zeroes.
The second problem is here:
while(_length--){
You are decrementing the value of length and also reading either its original or new value. Your linter is complaining because you are doing both. Doing so makes for code that is difficult to read. In particular, does the loop run length times or length - 1 times? It's not clear.
Your while loop always runs a fixed number of times, so from a stylistic point of view you would be better off with a for loop:
for (var i = 0; i < length; ++i) {
_retString += _charSet.charAt(Random(0, _charSet.length-1));
Delay(1);
}
As you're now only using ++ in the ++i statement within the for loop, this should avoid lint warnings.
I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?
Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.
It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);
Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.
let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.
Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo
As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.