newbie: logical 'or'

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
tabutcher
Forum Newbie
Posts: 20
Joined: Fri Aug 21, 2009 7:10 am

newbie: logical 'or'

Post 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); 
sureshmaharana
Forum Commoner
Posts: 30
Joined: Thu Jul 03, 2008 4:20 am
Contact:

Re: newbie: logical 'or'

Post 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);
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: newbie: logical 'or'

Post 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]
There are 10 types of people in this world, those who understand binary and those who don't
tabutcher
Forum Newbie
Posts: 20
Joined: Fri Aug 21, 2009 7:10 am

Re: newbie: logical 'or'

Post by tabutcher »

thank you thank you
I feel so dumb now :)
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: newbie: logical 'or'

Post 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]
There are 10 types of people in this world, those who understand binary and those who don't
tabutcher
Forum Newbie
Posts: 20
Joined: Fri Aug 21, 2009 7:10 am

Re: newbie: logical 'or'

Post by tabutcher »

thank you, I'll look into it :)
Post Reply