物件導向程式設計

 

 

    3.4 比較運算子

 

 


授課教師:陳慶瀚

WWW : http://www.miat.ee.isu.edu.tw/java

E-mail : pierre@isu.edu.tw   

 


Java has six relational operators that compare two numbers and return a boolean value. The relational operators are <, >, <=, >=, ==, and !=.

 

x < y

Less than

True if x is less than y, otherwise false.

x > y

Greater than

True if x is greater than y, otherwise false.

x <= y

Less than or equal to

True if x is less than or equal to y, otherwise false.

x >= y

Greater than or equal to

True if x is greater than or equal to y, otherwise false.

x == y

Equal

True if x equals y, otherwise false.

x != y

Not Equal

True if x is not equal to y, otherwise false.

Here are some code snippets showing the relational operators.

boolean test1 = 1 < 2;  // True. One is less that two.
boolean test2 = 1 > 2;  // False. One is not greater than two.
boolean test3 = 3.5 != 1;  // True. One does not equal 3.5
boolean test4 = 17*3.5 >= 67.0 - 42; //True. 59.5 is greater than 5
boolean test5 = 9.8*54 <= 654; // True. 529.2 is less than 654
boolean test6 = 6*4 == 3*8; // True. 24 equals 24
boolean test7 = 6*4 <= 3*8; // True. 24 is less than or equal to 24
boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

 

This, however, is an unusual use of booleans. Almost all use of booleans in practice comes in conditional statements and loop tests. You've already seen several examples of this. Earlier you saw this

 

if (args.length > 0) {
  System.out.println("Hello " + args[0]);
}

args.length > 0 is a boolean value. In other words it is either true or it is false. You could write

boolean test = args.length > 0;
if (test) {
  System.out.println("Hello " + args[0]);
}

instead. However in simple situations like this the original approach is customary. Similarly the condition test in a while loop is a boolean. When you write while (i < args.length) the i < args.length is a boolean.


課堂練習:

寫一程式,可輸入一個介於0和100的正整數score,使用if-else if-else語法,使得:

若score>=60,則輸出「及格」,

否則如果score>50,則輸出「補考」,

否則輸出「死當」。



 

物件導向程式設計

義守大學電機系 陳慶瀚

2001.10.02