Fork me on GitHub

竞猜商品

电视商品价格竞猜活动, 活动规则是:随机出现一个商品名,用户猜测它的价格,连续猜测5次,如果猜对便可获得此商品
提示:(1)定义GuessMachine,编写它的initial方法,预定义商品信息根据产生的随机数字,选定一款竞猜商品
(2)编写GuessMachine的guess方法,如果猜测正确,返回“猜对了,恭喜中奖!”,价格偏高,提示高了,偏低,提示低了。
(3)编写测试类模拟竞猜,产生随机数 Math.radom();只产生0.0~1.0之间的数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//GuessMachine
import java.util.Scanner;
public class GuessMachine {
String mach= null;
int price= 0;
public void initial(){
int data= (int)(Math.random()* 4);
switch(data){
case 0:
mach= "电视机";
price= 3359;
break;
case 1:
mach= "电冰箱";
price= 1243;
break;
case 2:
mach= "油烟机";
price= 4654;
break;
case 3:
mach= "ipthone";
price= 2324;
break;
case 4:
mach= "洗衣机";
price= 5643;
break;
default:
break;
}
// System.out.println(data);
// System.out.println("请输出"+ mach+ "的价格: ");
}
public void guess() {
Scanner inpScanner= new Scanner(System.in);
int guess= 0;//用户输入的价格
int i= 0;//用户猜价格的次数
while(i< 5){
System.out.println("请输入您竞猜的价格: ");
guess= inpScanner.nextInt();
if(price== guess){
System.out.println("猜对了,恭喜中奖!");
}else if(price> guess) {
System.out.println("低了,请高一点。");
}else if (price< guess) {
System.out.println("高了, 请低一点。");
}
i++;
}
if(i>= 5){
System.out.println("您已经猜奖5次,欢迎下次光临!");
}
inpScanner.close();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
//Test.java
package com.cnstrong.com;
public class Test {
public static void main(String[] args){
GuessMachine gMachine= new GuessMachine();
gMachine.initial();//初始化
gMachine.guess();
}
}
Your support will encourage me to continue to create!