一个类A有一个实例变量v,从键盘接受一个正整数作为实例变量v的初始值
另外再定义一个类B,对类A的实例变量v进行猜测
如果大了则提示大了
如果小了则提示小了
等于则提示测试成功
猜测数字比大小的测试:
/*** @author LBJ* @version V1.0* @Package PACKAGE_NAME* @date 2021/1/28 17:38* @Copyright 公司*/
public class Test01{public static void main(String[] args){A a=new A(100);B b=new B(a);java.util.Scanner s=new java.util.Scanner(System.in);while (true){System.out.println("请输入要猜测的数字");int caiCeNum = s.nextInt();b.cai(caiCeNum);}}
}class A {private int v;public A(){}public A(int v){this.v=v;}public int getV() {return v;}public void setV(int v) {this.v = v;}
}class B {//把A作为B的实例变量private A a;public B(){}public B(A a){this.a=a;}public A getA() {return a;}public void setA(A a) {this.a = a;}public void cai(int caiCeNum){int shiJiZhi=this.getA().getV();
// int shiJiZhi=a.getV();if(caiCeNum == shiJiZhi){System.out.println("猜测成功");}else if(caiCeNum > shiJiZhi) {System.out.println("猜大了");}else if(caiCeNum < shiJiZhi){System.out.println("猜小了");}}}
运行结果: