If Else Statement Disaster [duplicate] - javascript

This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
today I decided I wanted to make a simple js code that would accept a number (in meters), and decide what the appropriate metric unit to use would be. The code turned out to be a little more complicated than I had expected, but I was able to figure out most of the bugs as I found them (even if it meant rearranging all of my code). However, when it came to my if/else statement I could not figure it out. If I put in a number that is less than 1 nothing happens. If I put in a number more than 9 it logs the same thing every time. The structure itself may need some work, but if someone could help me with the if/else statement I would be very thankful. Here is the code (init is called when the body loads):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
if (0.1 >= x >= 0.99) {
console.log("deci");
}
else if (0.100 >= x >= 0.999) {
console.log("centi");
}
else if (0.1000 >= x) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x <= 99) {
console.log("deca");
}
else if (100 <= x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}

Use && as AND operator in javascript
Convert these 100 <= x <= 999 to 100 <= x && x <= 999

You could simplify the check a bit and return if a condition is true.
function convertDown(x) {
if (x < 0.01) {
console.log("milli");
return;
}
if (x < 0.1) {
console.log("centi");
return;
}
if (x < 1) {
console.log("deci");
return;
}
console.log("error");
}

Your code has 2 sort of errors. One was simple to fix, that you have to add && between two conditions in if statement.
Now coming to the other part, the less than 1 items. It needed a different logic. Well, your maths seems to be needing bit attention. 0.1 is same as 0.100 and is same as 0.1000
I have updated the code to look for the number of digits after the decimal point and then console.log accordingly.
The updated code will be:
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
// checks the number of digits after decimal point
decimals = (x.split('.')[1] || []).length
if (decimals == 1 || decimals == 2) {
console.log("deci");
}
else if (decimals == 3) {
console.log("centi");
}
else if (decimals == 4) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x && x <= 99) {
console.log("deca");
}
else if (100 <= x && x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Working jsfiddle example: https://jsfiddle.net/w7pf3moL/

A simplified version with only 1 method convert(float x):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convert(x) {
if (x < 0.01) console.log("milli");
else if (x < 0.1) console.log("centi");
else if (x < 1) console.log("deci");
else if (x < 10) console.log("meter");
else if (x < 100) console.log("deca");
else if (x < 1000) console.log("hecto");
else console.log("kilo");
}
function convertMetricMeters(x) {
if (x > 0) {
convert(x);
} else {
console.log("Appropriate Metric Unit");
}
}
}
init();

Related

A small syntactic problem in javascript- Tic Tac Toe

this is part of code in javascript for a Tic Tac Toe game. this part is checking win for diagonal in both directions. The diagonals work in X's winning but they do not work in O's winning. I basically wrote the same thing so I'm not sure what's the mistake I made.
Did I make some syntactic mistake?
function CheckWin_Diagonal(rowClicked, colClicked) {
if (rowClicked == colClicked) {
for (c = 0; c < rows; c++) {
if (intBoard[c][c] != X_CLASS)
break;
if (c == rows - 1) {
alert("PLAYER X WIN!!");
document.location.reload()
}
}
}
else {
if (rowClicked == colClicked) {
for (c = 0; c < rows; c++) {
if (intBoard[c][c] != CIRCLE_CLASS)
break;
if (c == rows - 1) {
alert("PLAYER O WIN!!");
}
}
}
}
}
function CheckWin_Diagonal2(rowClicked, colClicked) {
if (rowClicked + colClicked == cols - 1) {
for (r = 0; r < cols; r++) {
if (intBoard[r][(cols - 1) - r] != X_CLASS)
break;
if (r == cols - 1) {
alert("PLAYER X WIN!!");
document.location.reload()
}
}
}
else {
if (rowClicked + colClicked == cols - 1) {
for (r = 0; r < cols; r++) {
if (intBoard[r][(cols - 1) - r] != CIRCLE_CLASS)
break;
if (r == cols - 1) {
alert("PLAYER O WIN!!");
}
}
}
}
}
I haven't seen the logic at all, but you are doing:
function CheckWin_Diagonal(rowClicked, colClicked) {
if (rowClicked == colClicked) {
/** logic **/
}
else {
if (rowClicked == colClicked) {
/** logic **/
}
}
}
Obviously the code in the second if will never execute because it's the same condition as the first one (so it'll never get there).
You are basically saying:
IF SOMETHING HAPPENED DO THIS, OTHERWISE IF THE SAME THING HAPPENED DO THAT
So THAT will never happen, because you trapped the condition in the first IF and there's no OTHERWISE for the exact same condition
Your else blocks run the same if condition that triggered the else in the first place, guaranteeing they'll never run.

How do I select a select set of numbers in a loop?

Had to walk away from this one for the weekend. Would love to know my nemesis is giving me the answer plus some extra stuff? i want it to display 0 - 10
for (let i=-1; i++< 100; i*5) {
if (i < 0) {
continue;
} else if ( i > 50) {
break;
} else {
console.log(i/5);
}
}
Languages like Python will drop the remainder when using the / operator.
JavaScript won't, but you can get the same result with Math.floor().
for (let i = -1; i++ < 100; i * 5) {
if (i < 0) {
continue;
} else if (i > 50) {
break;
} else {
console.log(Math.floor(i / 5));
}
}

Calculate closest gift position using javascript

I tried one practice and check the requirement below.
You are on your way to find the gifts. All the gifts lie in your path in a straight line at prime
numbers and your house is at 0.
Given your current position find the closest gift to your position, and calculate the distance
between your current position and gift and tell the distance.
Ex:
For input 0, the output is 2
For number = 11, the output should be 0
For number = 2000000000, the output should be 11 For number = 1800000001, the output
should be 10
For the above logic I tried to use javascript and almost I have completed but i'm not getting the proper outpu as per the requirement,my output is returning any number.
Javascript
function isPrime(num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true
} else if (num % 2 === 0 || num % 3 === 0) {
return false
}
let i = 5
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
return false
}
i += 6
}
return true
}
HTML
<h1> Gift House</h1>
<label for="name">Enter a house Number</label>
<input type="text" id="inp" class="clr" />
<input type="button" id="checker" value="Calculate" onClick="findpos()">
<label for="name"> Distance of the gift house</label>
<input type="text" id="demo" value="" class="clr">
I understood your requirement,you have tried 2 steps properly but before those two steps you have to do one more logic to calculate prime number.Because you have called the function isPrime in your JS but where you defined the function?
Just include the below script in your JS code and check the output.
function findpos() {
var num = document.getElementById("inp").value;
var pos = 0;
while (true) {
if (isPrime(num)) {
break;
} else {
pos++;
num++;
}
}
document.getElementById("demo").value = pos;
}
Where is the isPrime function? how you called without defining the function.I think this is what the reason for your issue.
Check my below example,
function findpos() {
var num = document.getElementById("inp").value;
var pos = 0;
while (true) {
if (isPrime(num)) {
break;
} else {
pos++;
num++;
}
}
document.getElementById("demo").value = pos;
}
function isPrime(num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true
} else if (num % 2 === 0 || num % 3 === 0) {
return false
}
let i = 5
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
return false
}
i += 6
}
return true
}

Run multiple else if statements

When I run this code, only the INVALID (over 100) and High Distinction works. Any number below 80 also shows High Distinction. What have I done wrong?
function calculateGrade() {
var fvalue = Number(prompt('Please enter final score for unit. Enter a whole number only'));
document.write('The final score entered is ' + fvalue + '<br />');
if (fvalue > 100) {
document.write('INVALID');
} else if (80 <= fvalue <= 100) {
document.write('High Distinction');
} else if (70 <= fvalue <= 79) {
document.write('Distinction');
} else if (60 <= fvalue <= 69) {
document.write('Credit');
} else if (50 <= fvalue <= 59) {
document.write('Pass');
} else if (0 <= fvalue <= 49) {
document.write('Fail');
} else if (fvalue < 0) {
document.write('INVALID');
}
}
calculateGrade()
Your comparison syntax is invalid. You need to check one boundary at a time:
if (80 <= fvalue && fvalue <= 100) {
Same for the others.
To take it a step further, you only need to check one boundary, because the higher end is excluded by the else:
if (fvalue > 100) {
document.write('INVALID');
} else if (80 <= fvalue) {
document.write('High Distinction');
} else if (70 <= fvalue) {
// ...
This isn't java.
But you can surely try this.
else if ( (fvalue >= 80) && (fvalue<= 100)) {
document.write('High Distinction');

Problems with Modulo in JavaScript

Doing some practice runs on codecademy and came across the following problem: So the objective is to print "Fizz" if the numbers are divisible by 3. "Buzz" if the numbers are divisible by 5. And "FizzBuzz" if the numbers are divisible by both 3 and 5.
Here is my code, and I thought I had it right, but when I run it they tell me that my code is not 100% accurate. Looking to see any alternatives to this code, or what might be the issue...
Code:
for ( i = 0; i < 21; i++)
{
if (i % 3 == 0 )
{
console.log("Fizz");
}
if (i % 5 == 0)
{
console.log ("Buzz");
}
if ( i % 5 == 0 && i % 3 === 0)
{
console.log("FizzBuzz");
}
else
{
console.log(i);
}
}
You need to use else if to stop from other conditions executing:
for (var i = 1; i <= 20; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
It can easily be done in a one liner.
for (i = 1; i <= 20; i++) {
console.log(i%3?(i%5?i:'buzz'):(i%5?'fizz':'fizzbuzz'));
};
For a nice formatting also output i on each iteration:
for (i = 1; i < 21; ++i) {
console.log(i+": "+(i%3?(i%5?i:'buzz'):(i%5?'fizz':'fizzbuzz')));
};

Categories

Resources