if ( !(speed > 2000 && memory > 512) )
System.out.println("Reject this computer");
else
System.out.println("Acceptable computer");
(It would probably be better in this simple case to reverse the true-branch and the false-branch. But say that there were other considerations that made this undesirable.)
It is important to put parentheses around the entire expression whose true/false value you wish to reverse. Say that you are considering a computer with 2200 MHz speed and 750 Meg of memory. Evaluation proceeds like this:
! ( speed > 2000 && memory > 512 ) ------+------ -------+--- | | ! ( T && T ) ---------+----------- | ! ( T ) !T F
The NOT operator has high precedence, so it will be done first (before arithmetic and relational operators) unless you use parentheses. For example, without the parentheses in the above expression, this would happen:
!speed > 2000 && memory > 512 --+--- illegal: can't use ! on an arithmetic variable
Since !
has high precedence,
the compiler will try to apply it to speed
,
which won't work.
Sometimes using NOT can lead to confusion. Try to arrange the program logic to say directly what you want.
Look at the following:
if ( !( speed > 2000 && memory > 512 ) ) System.out.println("Reject this computer"); else System.out.println("Acceptable computer");
Fill in the blanks so that the following does the same thing:
if ( speed ____ 2000 ____ memory ____ 512 ) System.out.println("Reject this computer"); else System.out.println("Acceptable computer");