When will else condition executed ?? is there any possibility of i value which will not satisfy any if , else if condition and reach else block in javascript.
random = Math.random();
i=0; //0,0.1,0.001
console.log(random);
if(random < i) {
console.log("<");
} else if(random > i) {
console.log(">");
} else if(random == i) {
console.log("=");
}else{
console.log("nothing");
}
Else will never be reached. The Result of Math.random() is between 0 and 1 (see W3Schools)
Related
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.
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.
I have read about this error on other threads that mostly ask the user to remove semicolons. This seems to have no effect on my code.
function isEven(number){
if (number > 1)
return isEven(number-2);
else if (number == 1)
return false;
else if (number == 0)
return true;
else if (number < 0)
number *= -1
return isEven(number);
else
return "Error";
}
It seems that this line [number *= -1] is causing the error as if I remove it the code runs with no error except for negative numbers where the stack runs out of memory. What I'm trying to do is to make all numbers positive.
Anyone that would like to help me out?
Solution
function isEven(number){
if (number < 0){
number *= -1
return isEven(number);}
else if (number > 1){
return isEven(number-2);}
else if (number == 1){
return false;}
else if (number == 0){
return true;}
else
return "Error";
}
Short answer: Wrap your codes with {}
if (){
..
..
}else {
..
..
}
Long answer :
else if (number < 0)
number *= -1
return isEven(number);
You are not using {} hence the very next line of the condition only considered as a statement belong to the else if and the later will be treated as general statements.
Since you have 2 lines of code in else if, the link broken there and your else became an orphan. That is the reason you seeing the error. Please wrap up your conditions in {}
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1
return isEven(number);
}
else{
return "Error";
}
}
Note: Not only to avoid this specific error but to avoid many other weird things always try to use {}. That makes everyones life easy.
Problem is without curly brackets {}
Better you could add {}(curly brackets) on each if and else statement
function isEven(number) {
if (number > 1) {
return isEven(number - 2);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else if (number < 0) {
number *= -1
return isEven(number);
} else {
return "Error";
}
}
console.log(isEven(-2))
The problem is that you are trying to execute 2 lines of code in the 3rd else if without wrapping it up in curly braces.
By default only single line gets executed when you don't wrap up the block in curly braces.
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1;
return isEven(number);
}
else{
return "Error";
}
}
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();
I noticed something weird while reviewing this mergesort implementation on Code Review…
/************************************************************
* Mergesort implementation
***********************************************************/
function sort(array) {
var len = array.length;
var middle = Math.floor(len*0.5);
var left = array.slice(0,middle);
var right = array.slice(middle, len);
if (len == 1) {
return array;
} else {
}
return merge(sort(left), sort(right));
}
function merge(left, right) {
var a = left.length;
var b = right.length;
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else of (b == 0)
return left;
}
/************************************************************
* Demonstration
***********************************************************/
function doSort() {
var array = document.getElementById('in').value.split(/[, ]+/).map(function(e) {
return parseInt(e);
});
var sorted = sort(array);
document.getElementById('out').value = sorted;
}
function generateRandom(len) {
var array = [];
for (var i = 0; i < len; i++) {
array.push(Math.round(Math.random() * 100));
}
document.getElementById('in').value = array;
};
generateRandom(20);
<button onclick="generateRandom(20)">⬇︎ Generate random numbers ⬇︎</button>
<div><input id="in" size="80"></div>
<button onclick="doSort()">⬇︎ Sort ⬇︎</button>
<div><input id="out" size="80" disabled></div>
The last conditional branch is else of rather than else if. Normally, else of should result in a syntax error. Yet, no matter how hard I try, I can't trigger the syntax error — it always successfully returns an array sorted in descending order!
I know, else of (b == 0) could just be replaced by else, but still, I want to know: How could this code possibly work?
This works because of a combination of 2 "bad things" about Javascript: skipping braces in block statements that contain only a single statement, and semicolon insertion.
Your if statement, properly braced, should look like this:
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else of (b == 0) {
return left;
}
but, because of the missing braces and semicolon insertion, Javascript is seeing/parsing it like this:
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else {
of(b == 0);
}
return left;
If you always pass in legitimate left and right arrays then this last else branch is never reached, hence why you haven't seen an exception.
If you pass in an empty right array, it will reach the last branch and throw of is not a function:
merge([10, 20, 30], []);
Any respectable coding standard should explicitly require these 2 "features" of Javascript never be used... but that's just one opinion.
of is a keyword in ES6, used for iterating over objects..
but in this case the of is behaving as function not keyword..
The function code never goes to else of (b == 0) return left; part.. so compiler is not throw ReferenceError: of is not defined
if you will change of keyword into another word like else often(b==0).... then also code work
when you send right side empty then code will throw error ReferenceError: of is not defined, so finally this is only typo.