一、问题
猜数字游戏
一个类A有一个实例变量v,从键盘接收一个正整数作为实例变量v的初始值。
另外再定义一个类B,对A类的实例变量v进行猜测。
如果大了则提示大了
小了则提示小了
等于则提示猜测成功
二、代码
public class homework1{
public static void main(String[] args){
java.util.Scanner s1 = new java.util.Scanner(System.in);
A a1 = new A(s1.nextInt());
B b1 = new B(a1);
//java.util.Scanner s = new java.util.Scanner(System.in);
//int n = s.nextInt();
while(true){
java.util.Scanner s2 = new java.util.Scanner(System.in);
int n = s2.nextInt();
b1.cai(n);
}
}
}
class A{
private int v;
public A(){
}
public A(int v){
this.v = v;
}
public int getV(){
return this.v;
}
public void setV(int v){
this.v = v;
}
}
//类B里面有一个A型的实例属性
class B{
private A v;
public B(){
}
public B(A v){
this.v = v;
}
public A getV(){
return this.v;
}
public void setV(A v){
this.v = v;
}
public void cai(int ccs){
if(ccs > v.getV()){
System.out.println("猜大了");
}else if(ccs < v.getV()){
System.out.println("猜小了");
}else if(ccs == v.getV()){
System.out.println("猜对了");
System.exit(0);
}
}
}