猜数字游戏
- A类有一个实例变量v,从键盘接受一个正整数作为实例变量的初始值
- B类,对A类的实例变量v进行猜测
- 大了提示大,小了提示小,等于提示猜测成功
import java.util.*;
public class guessNum {
public static void main(String[] args) {
// TODO Auto-generated method stub
A a = new A(100);
B b = new B(a);
Scanner s = new Scanner(System.in);
while(true){
System.out.println("\n输入猜测的数字:");
int guess = s.nextInt();
b.guess(guess);
}
}
}
class A{
private int v;
public A() {}
public A(int v) {
this.v = v;
}
public void setV(int v) {
this.v = v;
}
public int getV(){
return this.v;
}
}
class B{
// 通过 B 猜测A
// 在B对象中有一个A对象的引用
private A a;
public B() {
}
public B(A a) {
this.a = a;
}
public void guess(int guessnum){
if (a.getV() == guessnum) {
System.out.println("猜对了");
System.exit(0); //退出JVM
}
else if (a.getV() < guessnum) {
System.out.println("猜大了");
}
else {
System.out.println("猜小了");
}
}
}