栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java猜数字游戏代码while(java猜数字游戏while循环)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java猜数字游戏代码while(java猜数字游戏while循环)

设计一个猜数字游戏

一个类A有一个实例变量v,从键盘接受一个正整数作为实例变量v的初始值。
另外,在定义一个类B,对A类的实例变量v进行猜测。
如果大了则提示大了。反之亦然,直至成功。


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;
  }
}

// 通过B猜A,在B中有一个A的对象引用
class B{

  // 把A作为B的实例变量
  private A a;

  public B(){}

  public B(A a){
    this.a = a;
  }

  public void setA(A a){
    this.a = a;
  }

  public A getA(){
    return this.a;
  }

  // 猜测方法
  public void call(int guessNum){
    int realNum = this.getA().getV();

    if (guessNum == realNum){
      System.out.println("win!");
      System.exit(0);
    } else if( realNum > guessNum){
      System.out.println("guess lesser");
    } else {
      System.out.println("guess bigger");
    }
  }
}

public class Test {
  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.print("Start to guess and input the guess number: ");
      int guessNum = s.nextInt();
      b.call(guessNum);
    }
  }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/775775.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号