I have an error in my school javascript project - javascript

I have multiple errors in my code. When I run the code, it gives an error saying that there is an unexpected identifier. Here is the full error, "SyntaxError: Unexpected identifier at /script.js:46:16". However, when I check through lines 46 through 16, I cant find any unclosed functions or methods. When I comment the if statement on line 46, it just gives an error on the other if statement. Can someone help me?
Heres the code:
function print(str){
console.log(str)
}
function farhToKelvin(far){
const cel = Math.floor(far / (9/5) - 32)
const kel = cel + 273
return kel
}
function farhToCelsius(far){
const cel = Math.floor(far / (9/5) - 32)
return cel
}
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(far / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(far / (9/5) - 32)
}
}
while (farh != "exit"){
var farh = prompt("enter a farhanhite tempature: ")
var type = prompt("convert it to celsius, or kelvin")
type.toLowerCase()
if (type == "celsius"){
const c = farhToCelsius(farh)
var val = convertToFarh(c)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
else if(type == "kelvin"){
const k = farhToKelvin(farh)
var val = convertToFarh(k)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
}

if (val > 50 or val == 50){
In Javascript, instead of or, we use ||. If you have a similar problem again, you might want to take a look at What does this symbol mean in JavaScript?

change
if (val > 50 or val == 50)
to this
if (val > 50 || val == 50)
or better to this
if (val >= 50)
there are similar problems on line 50 and 60 and 64
you need to update them all.
logically line 46 and 50 are the same. based on you print message the line 50 should be
if (val > 50 ) but line 45 should be if ( val <= 50)
so you have both syntax and semantic problems in your code to address

Here's a complete list of the issues you have in your code:
Using or instead of || (as others have stated)
Using incorrect variable name in the convertToFarh function
Omitting type parameter when calling convertToFarh
Attempting to call String.toLowerCase() on a number variable
Misspelling fahrenheit
Using or instead of || (Logical OR)
In your code, I believe you are intending to indicate if (val > 50 || val == 50) { instead of using or as used in other programming languages.
Before:
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
After:
if (val > 50 || val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 || val == 50){
print("it is hot, you should wear a tank top")
}
This logic also doesn't make sense. Perhaps you mean value < 50 in the first one and val >= 50 in the second?
You also repeat yourself whether you're converting to/from Kelvin or Celsius, so that code could be extracted out into its own function or just reduce the if..else blocks down to only affect the necessary variables and perform the comparison after these blocks.
Using incorrect variable name in convertToFarh function
In the convertToFarh function, you reference a variable named far, but there's no variable by that name. So you either mean to reference the val argument or you are trying to reference the fahr variable declared outside the function. In my code, I assume the former is the case val and rename it as follows:
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(val / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(val / (9/5) - 32)
}
}
Omitting type parameter when calling convertToFarh
In both function calls to convertToFarh, you use the c or k variable as the value of the val parameter, but you don't indicate the type. I have fixed this to indicate the type for each part:
var val = convertToFarh("celsius", c);
var val = convertToFarh("kelvin", k);
Attempting to call String.toLowerCase() on a number variable
In the convertToFarh function, you are attempting to call the String.toLowerCase() method on a number type (val) which gives an error. In my code, I simply commented this out and confirmed it can safely be removed.
Misspelling fahrenheit
It might not seem like a big deal, but making sure variables have proper spelling helps when others are reviewing your code (whether bug-fixing or general code review). I have fixed function names, variable names, and any references to fahrenheit in your code to be the proper spelling. This includes:
"enter a fahrenheit temperature: "
function fahrToKelvin and function calls
function fahrToCelsius and function calls
function convertToFahr and function calls
The variable named farh to fahr
Function parameters named far were changed to val to avoid variable name collision
Full code
function print(str) {
console.log(str);
}
function fahrToKelvin(val) {
const cel = (val - 32) / (9 / 5);
return Math.floor(cel + 273.15);
}
function fahrToCelsius(val) {
const cel = Math.floor((val - 32) * 5 / 9);
return cel;
}
function convertToFahr(type, val) {
if (type == "kelvin") {
return Math.floor(val / (5 / 9) - 459.67);
} else if (type == "celsius") {
return Math.floor(val / (9 / 5) + 32);
}
}
var fahr = prompt("enter a fahrenheit tempature: ");
var type = prompt("convert it to celsius, or kelvin");
type = type.toLowerCase();
if (type == "celsius") {
const c = fahrToCelsius(fahr);
var val = convertToFahr("celsius", c);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
} else if (type == "kelvin") {
const k = fahrToKelvin(fahr);
var val = convertToFahr("kelvin", k);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
}

Related

making a point counter for a dice game in javascript

I am trying to make a dice game point counter where you are awarded points based on how close your guess of what you thought the number was going to be to what the number rolled is. My current code looks like this
function continueL(e){
if (e.keyCode == Keyboard.letter('L')){
add(copter);
var evorod = readInt("What number do you think it's going to be? You are guessing ");
println("Please click the die to roll a number");
mouseClickMethod(contin);
}
}
function contin(e){
var num = Randomizer.nextInt(1,12);
println("The number rolled is.... " + num);
var numText = new Text("The number rolled is...." + num, "20pt Arial");
numText.setPosition(50, 200);
numText.setColor(Color.red);
add(numText);
if (num == evorod){
println("Congrats! You Win! Here is 100 points");
} else {
if(num == evorod - 1 || num == evorod + 1){
println("So close! Here is 80 points!");
} else {
if(num == evorod - 2 || num == evorod + 2){
println("Almost got it. Take 60 points!");
} else {
if(num == evorod - 3 || num == evorod + 3){
println("Nice try. Take 40 points!");
} else {
if(num == evorod - 4 || num == evorod + 4){
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
}
}
}
}
remove(copter);
}
But it only displays the final else no matter what your guess was vs the number rolled.
edit: evorod is a global variable
evorod needs global scope, right now it only exists inside the continueL() function so will be undefined when you try to use it in contin(). Fix that by declaring it outside the function.
Meanwhile your if statements could be simplified to this, instead of a bunch of separate nested conditionals:
if (num == evorod) {
println("Congrats! You Win! Here is 100 points"); // there is no println in javascript, I'll assume you've coded your own equivalent
} else if (num == evorod - 1 || num == evorod + 1) {
println("So close! Here is 80 points!");
} else if (num == evorod - 2 || num == evorod + 2) {
println("Almost got it. Take 60 points!");
} else if (num == evorod - 3 || num == evorod + 3) {
println("Nice try. Take 40 points!");
} else if (num == evorod - 4 || num == evorod + 4) {
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
Try a switch statement instead. There are 6 possible outcomes per throw. If you guessed less or more than the actual outcome you lose 20 points per digit away from the true outcome.
First of all, let's find how off your prediction was from the roll. We do that by subtracting (excuse my shabby math).
int outcome = ...
int guess = ...
int difference;
if(outcome > guess)
difference = outcome - guess;
else if(outcome < guess)
difference = guess - outcome;
switch(difference)
{
case 0:
{
System.out.println("100 Wondred points!");
break;
}
case 1:
{
System.out.println("You get 80 hamsters!");
break;
}
}
And so on it goes, with a difference of 5 being the lowest score because it means you were 5 numbers away from the outcome.

Grading Students in JS with recursion - Range Error

I was trying to work on this hackerrank problem.
Every student receives a grade in the inclusive range from
0-100 to .
Any less than 38 is a failing grade.
Sam is a professor at the university and likes to round each student's according to these rules:
If the difference between grade the and the next multiple of
5 is less than 3, round up to the next multiple of 5. If the value of grade is less than 38, no rounding occurs as the
result will still be a failing grade.
Given the initial value of for each of Sam's students, write code to
automate the rounding process.
My code is:
function gradingStudents(grades) {
const roundup = y => y + 1;
{
if ( grades < 38 || grades % 5 === 0) return grades;
else if ( grades % 5 < 4 && grades % 5 !== 0) return roundup(grades);
}
{
if (roundup % 5 === 0) return roundup;
else { gradingStudents(roundup + 1) }
}
}
gradingStudents(38) // -> 39
I tried to use Math.ceil(grades) inside the variable roundup but output didnt change. So, when you invoke the function with a number that is not before a multiple of 5 (e.g. 43) it returns the proceeding number. However, if it is the number before a multiple of 5 it gives a range error. "maximum call stack size reached."
As far as I got, the code doesnt proceed to the second part. Even if it did, I am not sure if it would fetch the current value of the function roundup when dealing with if statements in the second block.
What do I dont get in here?
Also, this is actually meant for an array output but since I am a beginner I am pretty much okay with this one for the start as well :D .
Javascript solution:
function gradingStudents(grades) {
return grades.map((grade) => {
if (grade > 37) {
const offset = 5 - (grade % 5);
if (offset < 3) {
grade += offset;
}
}
return grade;
});
}
Try this:
function gradingStudents(grades) { //input: 43
var finalGrade;
if(grade < 38)
return grades;
else{
var gradeDif = grades % 5; //3
if(gradeDif > 3){
return grades;
}
else {
return grades + (5 - gradeDif); //Output: 45
}
}
}
One solution calculates the next multiple of 5 no bigger than the grade and uses that value to test whether or not to round up (next5 - grade < 3).
We write a simple function to round an individual grade and then for a list of grades use .map with that function.
const roundGrade = (grade) => {
const next5 = 5 * Math.ceil (grade / 5)
return (grade < 38) ? grade : (next5 - grade < 3) ? next5 : grade
}
const gradingStudents = (grades) =>
grades .map (roundGrade)
console .log (gradingStudents ([73, 67, 38, 33]))
Note that, like most solutions to this problem, no recursion is needed.
1-Use the Array.prototypt.map according to the question logic.
const gradingStudents = (grades) => grades
.map(n => (n >= 38 && n % 5 >= 3)?(n + ( 5 - ( n % 5 ) )):n )
let result = gradingStudents([0,25,38,56,89,77,78,57,58])
console.log(result)
My solution is this
function gradingStudents(grades) {
grades.map((grade,i)=>{
if(grade >= 38){
let fg = (grade/5).toString().split('.');
if(fg[1]>5){
grades[i]=((parseInt(fg[0],10)+1) * 5);
};
}
});
return grades;
}
console.log(gradingStudents([73,67,38,33]));
my solution:
function gradingStudents(grades) {
return grades.map(function(grade) {
return (grade >= 38 && grade % 5 >= 3) ? grade + 5 - (grade % 5) : grade;
});
}

How NOT to break a function/loop on returning a value (Js)

Hey so I am making a 2D tile game, or really I am just messing around. I have made the map from an array, where 0 represents nothing, and other characters represents a walkable tile.
var map=[["t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t"],
["l","1","b","b","b","b","b","b","b","b","b","b","b","b","b","b","b","b","b","r"],
["l","r","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","r"],
["l","1","t","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","l","r"],
["l","1","1","t","t","t","t","t","t","t","t","t","t","t","t","r","0","0","l","r"],
["l","b","b","b","b","b","b","b","b","1","1","b","b","b","b","b","t","t","b","r"],
["0","0","0","0","0","0","0","0","0","l","r","0","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","0","0","l","r","0","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","0","0","l","r","0","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","0","l","1","1","r","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","l","1","1","1","1","r","0","0","0","0","0","0","0"],
["t","t","t","t","t","t","t","1","1","1","1","1","1","t","t","t","t","t","t","t"]];
On screen it looks like this
You see my moveable character here as well.
Now I have come this far, and I'd like my character to collide with the empty tiles represented as the value of 0 in my map array.
This is my code for checking collision (brackets are correct in the script):
function collisioncheck(ind){
for(var i in map){
for(var j in map[i]){
if(yass==true){
if(map[i][j]==0){
if(ind==0 && playerPosX==j*32+32 && playerPosY>i*32-32 && playerPosY<i*32+32){
return false;
}else if(ind==1 && playerPosX==j*32-32 && playerPosY>i*32-32 && playerPosY<i*32+32){
return false;
}else if(ind==2 && playerPosY==i*32+32 && playerPosX>j*32-32 && playerPosX<j*32+32){
return false;
}else if(ind==3 && playerPosY==i*32-32 && playerPosX>j*32-32 && playerPosX<j*32+32){
return false;
}else{
return true;
}
}
}else{
return true;
}
}
}
var yass=false;
function exist(){
for(var i in map){
for( var j in map[i]){
if(map[i][j]==0){
yass=true;
break;
}
}
}
So, this works. But only for the first 0 in the map. My problem is that the return statements breaks the for-loop and function. So my character will not collide with any other blank tile but the first one.
I will have to rewrite this, but is there any smart solution to this?
Link to jsfiddle here (Character not visible)
You're on the right track, your loop only runs for one iteration because you always return something after an iteration. However, you should only call return when you know the final result, because - as you said - it will exit the function.
It is correct to call 'return false' right away after a collision is detected, because if the player collides with at least one block, then there is a collision. On the opposite, 'return true' should only be called when you are sure that there are no collisions at all on the entire board, and you need to test every block on the map before you can confirm this.
function collisioncheck(ind) {
for (var i in map) {
for (var j in map[i]) {
if (yass == true) {
if (map[i][j] == 0) {
if (ind == 0 && playerPosX == j * 32 + 32 && playerPosY > i * 32 - 32 && playerPosY < i * 32 + 32) {
return false;
} else if (ind == 1 && playerPosX == j * 32 - 32 && playerPosY > i * 32 - 32 && playerPosY < i * 32 + 32) {
return false;
} else if (ind == 2 && playerPosY == i * 32 + 32 && playerPosX > j * 32 - 32 && playerPosX < j * 32 + 32) {
return false;
} else if (ind == 3 && playerPosY == i * 32 - 32 && playerPosX > j * 32 - 32 && playerPosX < j * 32 + 32) {
return false;
}
// else: do nothing. (i.e. let the loop run for the next block)
}
} else {
return true;
}
}
}
return true;
}
What we do here is go through all the blocks, if we find a collision we return false and exit the function. We only reach the 'return true' statement if we went through all the blocks without finding any collision, which is exactly what you want.
You need to use continue instead of return in the last else of your main if/else block on line 15

javascript value coming up empty not sure how to handle it

function updategeneral() {
//tmp = "fine_" + tmp + "_";
var actual = doc.findItem("1speed").value;
var posted = doc.findItem("2speed").value;
amt = "";
if (1speed != "" && 2speed != "") {
var a = 1 * 1speed;
var b = 1 * 2speed;
if (a - b <= 9) {
alert(amt);
amt = doc.getDefault("general_spb_1_to_15");
} else if (a - b <= 15) {
amt = doc.getDefault("general_spb_16_to_25");
} else if (a - b <= 25) {
amt = doc.getDefault("general_spb_15_to_19");
} else if (a - b <= 29) {
amt = doc.getDefault("general_spb_26+");
}
doc.findItem("mcare_amount").value = amt;
alert(doc.findItem("mcare_amount").value = amt);
}
}
Default values are:
general_spb_1_to_15=30.00 || general_spb_16_to_25=40.00 || general_spb_26+=50.00
My problem is when amt is empty or 0 it is always going to general_spb_1_to_15=30.00. I am not sure how to fix this- can someone please help? The values that I am using are 1speed = 20 and 2speed = 25 which is negative or empty.
Assuming your browser engine is interpreting 1speed and 2speed as variables (some will, some won't -- variable names aren't supposed to start with numbers so it would probably be wise to replace these with speed1 and speed2)...
But assuming that, then the case that you describe is seeing a value of a - b = -5 when processing your if statements, which means that it is being caught by
if (a - b <= 9) {
alert(amt);
amt = doc.getDefault("general_spb_1_to_15");
}
To change the result you are getting, you should add another option to the if statement structure. Perhaps:
if (b > a)
{
//do something for this special case
} else if (a - b <= 9) {
alert(amt);
amt = doc.getDefault("general_spb_1_to_15");
} else if ...
You may also want to specifically handle the case where one or both of speed1/speed2 are empty as an else on the outer if block.

Math calculation issue with Javascript

I am having a bit of trouble with a few math calculation in javascript.
The goal of this calculation is to generate a value when the user clicks on a text field.
For example:
1 Kilogram costs 32 cents to ship to America and the user wants to find out what 10KG will cost him which is $3.20. For this I have the following piece of javascript code:
function calculate(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) multiplyBy = 0.32;
if(num == 2) multiplyBy = 0.14;
if(num == 3) multiplyBy = 0.24;
if(num == 4) multiplyBy = 0.53;
var sum = parseInt(document.getElementById('weight'+num).value) * multiplyBy;
if(isNaN(sum)) return false;
price.value = sum;
}
The above code works perfectly fine, however when I reverse the process (someone has $3.20 and wants to find out how much KG he/she can ship with that (which is 10KG) the script returns: 9.375KG
The following code is used for this calculation:
function reverse(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) divideBy = 0.32;
if(num == 2) divideBy = 0.14;
if(num == 3) divideBy = 0.24;
if(num == 4) divideBy = 0.53;
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
if(isNaN(sum)) return false;
weight.value = sum;
}
I honestly don't grasp why it is failing, It would be much appreciated if someone could help me out with this.
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
You are forcing price into an integer before dividing it. So if price is 3.20, you are actually dividing 3 / 0.32, which is 9.375.
Don't force it into an integer.

Categories

Resources