/**
* 一个类A有一个实例变量v,从键盘接收一个正整数作为实例变量v的初始值。
* 另外再定义一个类B,对A类的实例变量v进行猜测。
* 如果大了则提示大了,小了则提示小了,等于则提示猜测成功
*/
public class 猜字游戏 {
public static void main(String[] args) {
java.util.Scanner ss = new java.util.Scanner(System.in);
System.out.print("请输入一个正整数作为被猜测的数字:");
int num = ss.nextInt();
// 创建A对象
A a = new A(num);
// 创建B对象
B b = new B(a);
// 开始猜测
java.util.Scanner s = new java.util.Scanner(System.in);
while (true) {
System.out.print("请输入您猜测的数字:");
// int caiCeNum = s.nextInt();
// b.cai(caiCeNum);
// 以上两行代码合并成一行
b.cai(s.nextInt());
}
}
}
class A{
private int v;
// 无参构造方法
public A() {
}
// 有参构造方法
public A(int v) {
this.v = v;
}
// set and get
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
}
class B{
// 把A作为B的实例变量 原因是在B里猜A,就需要让A和B建立起联系
private A a;
// 无参构造方法
public B() {
}
// 有参构造方法
public B(A a) {
this.a = a;
}
// set and get
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
// 猜的方法
public void cai(int caiCeNum){
// 实际数字(被猜测的数)
int shiJieShu = this.getA().getV();
if (caiCeNum == shiJieShu){
System.out.println("恭喜你,猜测成功!");
// 终止程序 退出JVM
System.exit(0);//这里使用return;不可以
// return;//return是退出猜的方法,但是没有退出循环。
} else if (caiCeNum < shiJieShu){
System.out.println("您猜小了,再来!");
}else {
System.out.println("您猜大了,继续!");
}
}
}