Javascript else if statement error - javascript

I have to make a javacript code that satisfy the triangle inequality theorem, which the two smaller sides adds up to be bigger than the largest side. I have to use javascript and use a prompt for users to enter three numbers. I can not ask the user to enter the largest number i have to find it by code. So below is what i got so far, but i keep getting an error at the first else if statement and so i wont run. Any idea whats wrong with my code?
<script type="text/javascript">
<!--
var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);
if(a>=b, a>=c){
if (b+c>a) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.1" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.1" );
}
else if(b>=c, b>=a) {
if (c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.2" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.2" );
}
}
else {
if (a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.3" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.3" );
}
}
}
// -->
</script>

if statements test a single condition, not multiple ones. Assuming you want to know that both a is greater than or equal to b AND a is greater than or equal to c, you need to use the && operator:
if(a>=b && a>=c)
If it's an OR, it's the || operator:
if(a>=b || a>=c)

There is no such thing
if(a>=b, a>=c){
If you want to check both for true, use:
if (a >= b && a >= c)
If you want to check either or:
if (a > = || a >= c)
But in general, this code looks really bad.

if ((a >= b) && (a >= c))
Search Google for "javascript if" or something like that to learn more.
I've also noticed that your problem is very different from your answer. You say you have to ask for two sides and compute the third, but in your answer you ask for all three and just inform the user if they got the values right...

Do you have to use an if statement.
var input2 = [10, 30, 50, 150];
input2.sort(function(a, b){return b-a});
console.log(input2[0]);
You can run this in firebug console of firefox to see what it does. Corrected my answer.

Thanks guys I know my code is sloppy, but I am just starting out so in time I will get better. Here is the way i fixed the code.
<script type="text/javascript">
<!--
var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);
if(a>=b && a>=c && b+c>a){
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else if(b>=c && b>=a && c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else if(c>=a && c>=b && a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality." );
}
// -->
</script>

Related

Prefix notation string calculator Javascript problem

I'm making a calculator for a prefix notation string and it has covered all the normal tests that I've added to it. But I've come across one that it doesn't seem to be getting the right answer for and I'm unsure of why it seems to be having a problem with this.
I think it might have something to do with the division and subtraction when it comes to the numbers, because apart of the problem was I needed to assume that all inputs were valid, so there wouldn't be negative numbers nor would there be bad inputs IE not formatted correctly.
Here is the code and some of the test problems I inputted into it.
"+ / * 1 3 + 12 16 * 10 4" = 40.107142857142854
"+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4" = 24.00267857142857 --- This is the one it doesn't like
"/ 300000 * + 12 16 * 10 40"= 26.785714285714285
function prefixEval(expression) {
let temp = expression.split(' ')
let expr = temp.reverse()
let stack = []
for (let i = 0; i < expr.length; i++) {
if (
expr[i] === '+' ||
expr[i] === '-' ||
expr[i] === '/' ||
expr[i] === '*'
) {
let j = stack.pop()
let k = stack.pop()
let temp = checkOperator(parseInt(j), parseInt(k), expr[i])
stack.push(temp)
} else {
stack.push(expr[i])
}
}
return stack
}
function checkOperator(a, b, op) {
switch (op) {
case '+':
console.log('adding' + ' ' + a + ' ' + op + ' ' + b)
console.log(a + b)
return a + b
case '-':
console.log('subtracting' + ' ' + a + ' ' + op + ' ' + b)
console.log(a - b)
return a - b
case '/':
console.log('dividing' + ' ' + a + ' ' + op + ' ' + b)
console.log(a / b)
return a / b
case '*':
console.log('multiplying' + ' ' + a + ' ' + op + ' ' + b)
console.log(a * b)
return a * b
default:
return 'this is not correct'
}
}
console.log(prefixEval('+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4'))
You are using parseInt and dividing 2 by 0 which produces Infinity . To fix,
Change,
let temp = checkOperator(parseInt(j), parseInt(k), expr[i])
to
let temp = checkOperator(parseFloat(j), parseFloat(k), expr[i])
This is give you the expected answer

Javascript giving two different results for the same thing. Accessing arrays using a numeral and a variable

$(document).ready(function() {
pages = new Array(4);
pages[0] = "here";
pages[1] = "is";
pages[2] = "some";
pages[3] = "data";
j = 1;
y = j + 1;
pages[y] = pages[j].slice(2);
$(".output").text(j + " ::: " + (pages[2] != undefined) + " ::: " + (pages[y] != undefined));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="output">text</div>
j = 1; y = j + 1;
console.log(j + " ::: " + (pages[2] != undefined) + " ::: " +
(pages[y] != undefined));
returns 1 ::: false ::: true
This bug has got me. I can't figure out why the same number used in these two different ways has a different result. It's causing me a headache.
Turned out that 'j' above was actually a string. I didn't convert to an integer after reading from $().attr().

My code isn't recognizing a condition

I am trying to solve this following problem (Udacity's Intro to Javascript):
Directions:
Write a loop that prints out the following song. Starting at 99, and ending at 1 bottle.
Example:
99 bottles of juice on the wall! 99 bottles of juice! Take one down, pass it around... 98 bottles of juice on the wall!
98 bottles of juice on the wall! 98 bottles of juice! Take one down, pass it
around... 97 bottles of juice on the wall!
...
2 bottles of juice on the wall! 2 bottles of juice! Take one down, pass it around... 1 bottle of juice on the wall!
1 bottle of juice on the wall! 1 bottle of juice! Take one down, pass it around... 0 bottles of juice on the wall!
and my code doesn't appropriately output the last line (it doesn't include "s" after "bottle"):
My code looks like this:
var num = 99;
while (num >= 1) {
num == 1 ? ((plural = "") && (nextPlural = "s")) :
num == 2 ? ((plural = "s") && (nextPlural = "")) :
((plural = "s") && (nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + "bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
why is this code ignoring my condition for "num == 2?" at the last line of output?
FYI, I was able to solve this using the following code, but it didn't look clean so I wanted to optimize this:
var num = 99;
var plural = "s";
var nextNum = num - 1;
var nextPlural = "s";
while (num >= 1) {
if (num > 1 && nextNum > 1){
plural = "s";
nextPlural = "s";
}
else if (num > 1 && nextNum == 1){
plural = "s";
nextPlural = "";
}
else if (num == 1 && nextNum <= 1){
plural = "";
nextPlural = "s";
}
console.log(num + " bottle" + plural + " of juice on the wall! " + num + " bottle"+ plural + " of juice! " +
"Take one down, pass it around... " + nextNum + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1;
nextNum = num - 1;
}
Alright, so the question, if I understand it right, is why the last line for the first code sample outputs "0 bottle" instead of "0 bottles".
So let's translate what you attempted to achieve with your code into English and figure out what the interpreter does:
Set num to 99.
While num greater or equal to 1, do the following:
2.1 If num equals 1, set plural to "" and nextPlural to "s".
2.2 Else if num equals 2, set plural to "s" and nextPlural to "".
2.3 Else set both plural and nextPlural to "s".
The console output is trivial, so I won't mention it here.
Set num equal to num-1.
You might notice that substituting the ternary operator with an if statement yields the correct result:
var num = 1;
var plural = '';
var nextPlural = '';
while (num >= 1) {
if(num==1) { plural = ''; nextPlural='s'; }
/*num == 1 ? ((plural = "") && (nextPlural = "s")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));*/
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
What does that mean? That there is a syntax error with your use of the ternary operator. What could it possibly be? Let's declare a new variable and try setting and outputting it along with the others.
var num = 1;
var plural = '';
var nextPlural = '';
var test = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? ((plural = "") && (nextPlural = "s") && (test = "test")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
console.log(test);
num = num - 1
}
You will notice that test remains equal to an empty string, just like nextPlural. That's because using && is not the correct way of instantiating variables inside ternary constructions, so this code will work as intended:
var num = 99;
var plural = '';
var nextPlural = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? (plural = "", nextPlural = "s") : (num == 2 ? (plural = "s", nextPlural = "") : (plural = "s", nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
--num;
}
If you are interested, this is how I would probably program the solution:
for(var i=99, w=' on the wall!'; i>0; i--) {
console.log(returnEmpties(i)+w+' '+returnEmpties(i)+'! Take one down, pass it around... '+returnEmpties(i-1)+w);
}
function returnEmpties(n) { return n+' bottle'+(n==1?'':'s')+' of juice'; }
The ternary operator stuff is just a big mess, I've tried to figure it out, but it's really worth trying to fix since it's just not a good idea to use ternary operators like that. You've nested a ternary inside another ternary and basically have an if, else if, else condensed into 3 lines.
You can avoid doing extra logic and realize that you need only add an 's' when the number is not 1.
By extracting this logic into a function that returns the string 's' or the empty string '', you can simply plug this function into your loop and provide it with n and n-1.
function plural(n) {
return n == 1 ? '' : 's'; // note this is the appropriate usage of a ternary operator
}
You can then simply your loop to just
while (num >= 1) {
console.log('...'); // left as an exercise for you to fill in the required function call and string concatenations.
num--; // same thing as num = num - 1;
}

Compare numbers in Array using for loop

I have a prob to solve, I have to use a loop to step through each position in
an array of " winning numbers"to check whether the variable customer number (input from keyboard) matches any of the winning numbers.
I must use a For loop to step through each position in the winning numbers array and to compare the customer number to each number the array contains.
I cannot use any method to achieve this problem
Thanks for your help!
here what I did so far:
var customerNumbers = prompt("Enter your number:");
var winningNumbers = [12, 17, 24, 37, 38, 43];
for (var i = 0; i < winningNumbers.length; i++) {
if (customerNumbers == 12 || //condition determinates the winning numbers
customerNumbers == 17 ||
customerNumbers == 24 ||
customerNumbers == 37 ||
customerNumbers == 38 ||
customerNumbers == 43)
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!");
} else {
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week");
}
You should use indexOf() to check whether customerNumbers exists in winningNumbers
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Script
var customerNumbers=prompt("Enter your number:" );
var winningNumbers=[12, 17, 24, 37, 38, 43];
if (winningNumbers.indexOf(parseInt(customerNumbers, 10)) > -1)
alert("This week Winning numbers are:"+"\n"+"\n"+winningNumbers+"\n"+"\n"+"The customer's Number is:"+"\n"+"\n"+customerNumbers+"\n"+"\n"+"We have a match and a winner!");
} else {
alert("This week Winning numbers are:"+"\n"+"\n"+winningNumbers+"\n"+"\n"+"The customer's Number is:"+"\n"+"\n"+customerNumbers+"\n"+"\n"+"Sorry you are not a winner this week");
}
Below solution loops all the winning numbers and check for a match
var customerNumbers = prompt("Enter your number:");
var winningNumbers = [12, 17, 24, 37, 38, 43];
var match = false;
for (var i = 0; i < winningNumbers.length && !match ; i++) {
if (winningNumbers[i] == customerNumbers) {
match = true;
}
}
if (match)
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!");
} else {
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week");
}

How would I create a function that takes three numbers as arguments and returns the largest of them?

I've been looking at simple JS exercises and I would appreciate it if you showed me how to approach this question or, even better, provide a solution that I can take a look at. Help much appreciated.
EDIT: I would also appreciate any simple working example of the function in use.
function whatDidYouTry() {
return Math.max.apply(null, arguments);
}
There's no need to create a new function as one already exists:
Math.max(num1, num2, num3);
Creating a new function is just extra overhead with no value added.
function get_max(num1, num2, num3)
{
var max = Math.max(num1, num2, num3);
return max;
}
alert(get_max(20,3,5)); // 20
DEMO.
​
Taking a crack at it.
function threeNumberSort(a,b,c) {
if (a<b) {
if (a<c) {
if (b<c) {
console.log(a + ", then " + b + ", then " + c);
} else {
console.log (a + ", then " + c + ", then " + b);
}
} else {
console.log (c + ", then " + a + ", then " + b);
}
} else {
if (b<c) {
if (a<c) {
console.log (b + ", then " + a + ", then " + c);
} else {
console.log (b + ", then " + c + ", then " + a);
}
} else {
console.log (c + ", then " + b + ", then " + a);
}
}
}
threeNumberSort(1456,215,12488855);
This will print on your console:
215, then 1456, then 12488855
I have used the algorithm I found on this page. More efficient ones probably exist out there.
This is the manual code I came up with using functions and else if statements:
function maxOfThree(a, b, c) {
if ((a >= b) && (a >= c)) {
return a;
} else if ((b >= a) && (b >= c)) {
return b;
} else {
return c;
}
}
console.log(maxOfThree(343,35124,42));

Categories

Resources