猜数字游戏
一个类A有一个实例变量v,从键盘接收一个正整数作为实例变量v的初始值。
另外再定义一个类B,对A类的实例变量v进行猜测。
如果大了则提示大了
小了则提示小了
等于则提示猜测成功
public class caiTest{
public static void main(String[] args){
//创建A对象
A a1 = new A();
//输入一个正整数
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.println("请输入一个正整数:");
int m =s.nextInt();
if(m <= 0){
System.out.println("输入的数字不合法,请重新输入!!");
return ;
}
//将该数赋给A类中
a1.setA(m);
//创建B对象
B b1 = new B(a1);
//输入猜测的数字
java.util.Scanner s1 = new java.util.Scanner(System.in);
while(true){
System.out.println("请输入你猜测的正整数大小:");
int caiCeNum=s1.nextInt();
b1.cai(caiCeNum);
}
}
}
class A{
private int x;
//无参构造函数
public A(){
}
//有参构造函数
public A(int x){
this.x=x;
}
public void setA(int x){
this.x=x;
}
public int getA(){
return x;
}
}
class B{
private A y;
//无参构造函数
public B(){
}
//有参构造函数
public B(A y){
this.y=y;
}
public void setB(A y){
this.y=y;
}
public A getB(){
return y;
}
//猜测的方法
public void cai(int caiCeNum){
//实际数字
int realnum=y.getA();
if(caiCeNum == realnum ){
System.out.println("猜测的数字等于实际的数字");
//终止程序的执行
//退出JVM
System.exit(0);//强制退出
}
else if(caiCeNum > realnum ){
System.out.println("猜测的数字大于实际的数字");
}
else{
System.out.println("猜测的数字小于实际的数字");
}
}
}
运行结果: