##首先对题目进行分析:##
- 准备一批用来竞猜的商品
- 随机获取一件商品
首先我们先定义一个商品归属类 Good
public class Good {
String name; //商品名称
double price; //商品价格
public Good(String name, double price) { //有参构造
this.name = name;
this.price = price;
}
public Good() {
}
}
##编写一个QuessGood类 其中的initial()方法预定义商品信息,根据产生的随机数字,选定一款竞猜的商品,编写guess()方法如果猜测正确,返回“猜对了!”;如果偏大,返回“再小些”;如果偏小,返回“再大些!4次没猜对返回 下次努力##
###其中会用到随机数的知识###
通过Math.random()方法可以生成[0,1)区间,可以为0,但是小于1。其他通常的使用方式如下 int index= (int) Math.floor(Math.random()*3); 就是求0-3之间的随机数 利用floor 转换int 进行向下取整数就可以得到0-2之间的随机数
-编写 initial()方法
public static Good initial(){
//
Good g1=new Good("洗衣机",5000.0);
Good g2=new Good("吹风机",8000);
Good g3=new Good("电动牙刷",500);
//将对象存入数组
Good [] gs={g1,g2,g3};
int index= (int) Math.floor(Math.random()*3);
return gs[index];
}
- 编写guess方法进行判定–主要要注意的就是当4次没猜对的时候就不在返回再猜一次直接返回下次努力吧
public static void guess(Good good){ //这里的参数是传入initial方法中随机出的商品(对象)
Scanner sc = new Scanner(System.in);
System.out.println("请输入"+good.name+"的价格");
int i=0;//计次数
do{
int x=sc.nextInt();
if (good.price==x){
System.out.println(good.name+"拿走吧");
return; //猜中后直接拿走
}else if (good.price>x){
System.out.println("再大点!");
}else System.out.println("在小点!");
if (i<3) System.out.println("再猜一次吧"); //前三次就输出在猜一次
i++;
}while (i<4);
System.out.println("4次没有猜对下次努力吧");
}```
- 编写测试类模拟竞猜
public static void main(String[] args) {
//随机出一个商品
Good g=initial();
//猜价格
guess(g);
}
- 整体代码如下 (测试类与QuessGood放在一起了)
public class QuessGood{
//随机出一个商品
public static Good initial(){
//
Good g1=new Good("洗衣机",5000.0);
Good g2=new Good("吹风机",8000);
Good g3=new Good("电动牙刷",500);
//将对象存入数组
Good [] gs={g1,g2,g3};
int index= (int) Math.floor(Math.random()*3);
return gs[index];
}
public static void guess(Good good){
Scanner sc = new Scanner(System.in);
System.out.println("请输入"+good.name+"的价格");
int i=0;//计次数
do{
int x=sc.nextInt();
if (good.price==x){
System.out.println(good.name+"拿走吧");
return;
}else if (good.price>x){
System.out.println("再大点!");
}else System.out.println("在小点!");
if (i<3) System.out.println("再猜一次吧");
i++;
}while (i<4);
System.out.println("4次没有猜对下次努力吧");
}
public static void main(String[] args) {
//随机出一个商品
Good g=initial();
//猜价格
guess(g);}}
运行效果: