分类:
2008-09-12 09:09:15
至此,在每一个方法中,我们都只用到了顺序执行,语句一条接一条地执行。与其他语言一样, (TM) 也提供了条件执行的语言结构:if, switch 以及条件执行运算符"?"。
Conditional Constructs |
if ( else |
switch ( case break; more-case-statement-break-groups... default: } |
( |
if 语句更常用的的结构如下:if :
if ()
...
此处
x = 4;
也可以是用 “{” 和 “}” 括起来的多条语句(一个语句组), 例如,
{
x = 4;
y = 6;
}
而
Boolean Expression | Interpretation |
x < 3 | x is less than 3 |
x == y | x is equal to y |
x >= y | x is greater than or equal to y |
x != 10 | x is not equal to 10 |
variable is true |
如果布尔表达式的值为 true,那么,if 子句后的语句(或者语句组)将被执行。
也支持可选的 else 子句;其语法是:
if ()
...
else
...
如果布尔表达式的值为 true,if 子句后的语句(或语句组)将被执行;否则,将执行else 子句后的语句(或语句组)。
布尔表达式一般包含一个或多个 Java 的比较运算符。Java 的比较运算符如下表中所示的:
Comparison Operator | Interpretation |
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
== | equal to |
!= | not equal to |
下面回头看看我们的用户定义类型 Dog,为了更好的表示真实世界的对象,我们可以再添加一些状态变量。假设我们添加的实例变量为 gentle 和 obedienceTrained,二者的值可为 true 或 false:
class Dog {
String barkSound = new String("Woof.");
boolean gentle = true;
boolean obedienceTrained = false;
...
Java 中,布尔型值是字面值(注意字母的大小写),boolean 变量能接受两种值。对 gentle 和 obedienceTrained 我们没有使用 new 运算符,因为我们不是创建对象--而是使用原始数据类型的变量并赋给默认值 true 和 false。
写方法(Access methods) 为我们提供了灵活更改实例变量的办法:
void setGentle(boolean gentle) {
this.gentle = gentle;
}
void setObedienceTrained(boolean trained) {
obedienceTrained = trained;
}
注意,在 setObedienceTrained() 中对 obedienceTrained 的引用并没有使用 this 限制符,因为此处并没有同名的局部变量。