因为第二章和第三章的泳池迷宫比较简单,所以这一次放在一起发。
2 拜访对象村
class Echo {
int count = 0;
void hello() { //hello方法
System.out.println("helloooo... ");
}
}
public class EchoTestDrive {
public static void main(String[] args) {
Echo e1 = new Echo();
Echo e2 = new Echo();
int x = 0;
while (x < 4) { //运行结果有四行hello,所以循环了四次
e1.hello(); //每次循环调用一次hello方法
e1.count = e1.count + 1;
if (x > 0) { //第一次循环x=0,之后三次此条件都满足
e2.count = e2.count + 1;
}
if (x > 1) { //前两次循环不满足条件x>1
e2.count = e2.count + e1.count;
}
x = x + 1;
}
//最后输出e2的count的值
System.out.println(e2.count);
}
}
//运行结果:
helloooo...
helloooo...
helloooo...
helloooo...
10
3 认识变量
public class Triangle {
double area;
int height;
int length;
public static void main(String[] args) {
int x = 0;
Triangle[] ta = new Triangle[4]; //创建对象数组
while (x < 4) {
ta[x] = new Triangle();
ta[x].height = (x + 1) * 2;
ta[x].length = x + 4;
ta[x].setArea(); //调用setArea方法给area赋值
System.out.print("trianglr " + x + ", area");
System.out.println(" = " + ta[x].area);
x = x + 1;
} //循环结束,x此时为4
int y = x; //将4赋给y
x = 27; //虽然x发生了变化,但是y没有重新赋值所以还是4
Triangle t5 = ta[2];//ta[2]和t5都引用相同对象
ta[2].area = 343; //改变ta[2]的area的值,t5的area也发生了改变
System.out.print("y = " + y);
System.out.println(", t5 area = " + t5.area);
}
void setArea() { //setArea方法
area = (height * length) /2;
}
}
//运行结果:
trianglr 0, area = 4.0
trianglr 1, area = 10.0
trianglr 2, area = 18.0
trianglr 3, area = 28.0
y = 4, t5 area = 343.0