现有电视商品价格竞猜活动,活动的规则:随机出现一个商品名,用户猜测它的价值,如果在规定次数内猜对,便可获得此商品。模拟竞猜活动,运行结果如下所示: (选作)
分析:
1、准备一批用来竞猜的商品
2、随机获取一件商品
Java程序:
1、定义对象所归属的类:商品类–Goods(属性: 商品的名称String name 商品对应的实际单价 int price)
2、模拟购入一批商品
多个Goods对象
3、
请猜测“公主电动车”的价格:1000
再大点!
再猜一次吧:5000
再小点!
再猜一次吧:2500
在小点!
再猜一次吧:2200
4次内没有猜对,下次努力吧!
创建一个主类放在包DEMO下面
package DEMO;
import java.util.Scanner;
public class OnessMechine {
public static void main(String[] args) {
String name=initial().name;
int price=initial().price;
System.out.println(name + "" + price);
Guess(name,price);
}
private static Goods initial() {
Goods goods1 = new Goods("冰箱", 2000);
Goods goods2 = new Goods("洗衣机", 2200);
Goods goods3 = new Goods("空调", 1000);
Goods goods4 = new Goods("电话", 7000);
Goods goods5 = new Goods("电脑", 5000);
Goods[] gs = new Goods[5];
gs[0] = goods1;
gs[1] = goods2;
gs[2] = goods3;
gs[3] = goods4;
gs[4] = goods5;
int b = (int) Math.floor(Math.random() * 5);
Goods goods = gs[b];
return goods;
}
public static void Guess(String name, int price) {
Scanner scanner = new Scanner(System.in);
int i = 0;
for (; i < 4; i++) {
int a = scanner.nextInt();
if (a > price) {
System.out.println("猜大了,再小一点");
} else if (a < price) {
System.out.println("猜小了,再大一点");
} else if (a == price) {
System.out.println("猜对了,送" + name + "你了");
break;
}
}
if (i == 4)
System.out.println("猜了4次了,不能猜了");
}
}
创建一个Goods类放在DEMO包下面
package DEMO;
public class Goods {
String name;
int price;
public Goods(String name,int price){
this.name=name;
this.price=price;
}
}
原博客地址



