Page 1 of 1

newbie: logical 'or'

Posted: Thu Nov 05, 2009 7:09 pm
by tabutcher
hello,
my while loop runs forever and I can't seem to solve the problem. I think the problem is with my while condition. Just need someone to take a look and see what is wrong.

thanks in advance :)

Code: Select all

 var operator, num1, num2, answer;num1 = parseFloat(prompt("enter number 1", ""));num2 = parseFloat(prompt("enter number 2", ""));do{operator = prompt("enter a for addition, s for subtraction", "");}while(operator != "a" || operator != "s"); if(operator == "a"){    answer = num1 + num2;}else{    answer = num1 - num2;}document.write(answer); 

Re: newbie: logical 'or'

Posted: Fri Nov 06, 2009 1:26 am
by sureshmaharana
Hey,

Your loop is wrong, Try this.

var operator, num1, num2, answer,flg;
num1 = parseFloat(prompt("enter number 1", ""));
num2 = parseFloat(prompt("enter number 2", ""));
flg = 0;
do
{
operator = prompt("enter a for addition, s for subtraction", "");
if(operator == "a" || operator == "s")
flg = 1;
}while(flg == 0);

if(operator == "a")
{
answer = num1 + num2;
}
else
{
answer = num1 - num2;
}
document.write(answer);

Re: newbie: logical 'or'

Posted: Fri Nov 06, 2009 3:28 am
by VladSun

Code: Select all

x1 || x2 = !(!x1 && !x2)
x1 && x2 = !(!x1 || !x2)
In your case you have:

Code: Select all

!x1 || !x2
which is

Code: Select all

!(x1 && x2)
because x1 and x2 can't be both true at the same time (operator can be either 'a' or 's') you have !(false) which is always true.

You need to use one of these:

[js]operator != "a" && operator != "s"[/js]
[js]!(operator == "a" || operator == "s")[/js]

Re: newbie: logical 'or'

Posted: Fri Nov 06, 2009 4:26 am
by tabutcher
thank you thank you
I feel so dumb now :)

Re: newbie: logical 'or'

Posted: Fri Nov 06, 2009 4:54 am
by VladSun
You can always use the "multiplexer" approach ;) (a lookup table)
http://en.wikipedia.org/wiki/Multiplexer

[js]var permitted = {    'a' : true,    's' : true,};do{operator = prompt("enter a for addition, s for subtraction", "");}while(!petmitted[operator]);[/js]

Re: newbie: logical 'or'

Posted: Sat Nov 07, 2009 12:19 am
by tabutcher
thank you, I'll look into it :)