Monday, July 27, 2009

Please Help - Java Programming Question?

I have no idea why the "if" statement is valud, thus allowing for the infinite loop to execute. Someone please help. I am very frustrated.





public class test


{





public static void main (String args[]) {





int a,b,c,d;


a = 10;


b = 20;





c = 10;


d = 15;





if(((a %26amp; b) %26lt; (c %26amp; d)) | ((a %26amp; b) %26gt; (c %26amp; d)) )


{


for(;;)


System.out.println("asdf");


}


}


}

Please Help - Java Programming Question?
IMHO it may be that you are using the boolean logic in the wrong way.





My way of thinking is that you want a test to see if 'a' and 'b' are less than 'c' and 'd' OR 'a' and 'b' are greater than 'c' and 'd'.





If this is the way you want it, you need to write the if statement like this


if (((a %26lt; c) %26amp;%26amp; (a %26lt; d) %26amp;%26amp; (b %26lt; c) %26amp;%26amp; (b %26lt; d)) || ((a %26gt; c) %26amp;%26amp; (a %26gt; d) %26amp;%26amp; (b %26gt; c) %26amp;%26amp; (b %26gt; d))) { ... }





Whatever the way you want to do it, the for loop will cause the infinite loop to happen.





for(;;)


System.out.println("asdf")





has no way of stopping, once the condition in the if statement is true.
Reply:Terminate for loop you means instead of for(;;) write for(i=0;i%26lt;HowManyTimesYouWantToExecute;i...


Good luck
Reply:im having problems with Java too.. i can help you but im kinda lazy to think right now... sowee...





... and GoodLuck...
Reply:simply convert the values into binary and do as needed





a=10=001 000


b=20=010 000





c=10=001 000


d=15=001 101





for a %26amp; b = 000 000 (Logical AND operation)


c %26amp; d = 001 000





therefore 000 000 %26lt; 001 000


(a%26amp;b) %26lt; (c%26amp;d)





first condition satisfies and it is ORed with next instruction so it doesn't matter condition satisfies or not





therefore if condition satisfies and goes to the loop


No comments:

Post a Comment