有四种水果(苹果,香蕉,西瓜,橘子)
1、给每种水果设定一个商品号,商品号是8个0-9的随机数,号码不能重复
2、根据商品号查询对应的商品。
如果查不到输出:“查无此商品”
如果能查到打印:”根据商品号:12345678,查询到对应的商品为:西瓜”
---------------------------------------------------------------------------------------------
package com.heima.tests;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.text.StyledEditorKit.ForegroundAction;
public class Test05 {
public static void main(String[] args) {
Random r = new Random(6000);
String[] str = new String[4];
StringBuffer sb = new StringBuffer();
HashSet<String> ls = new HashSet<>();
for (int i = 0; i < 4; i++) {
sb.delete(0, sb.length());
ls.clear();
while (ls.size() < 8) {
int num = r.nextInt(10);
if (!ls.contains(num + "")) {
ls.add(num + "");
sb.append(num + "");
}
}
str[i] = sb.toString();
}
TreeMap<String, String> tm = new TreeMap<>();
tm.put(str[0], "西瓜");// 53872106
tm.put(str[1], "苹果");// 47658392
tm.put(str[2], "橘子");// 93018742
tm.put(str[3], "香蕉");// 03718254
System.out.println("请输入商品号:");
String st = new Scanner(System.in).nextLine();
if (tm.keySet().contains(st)) {
System.out.println("根据商品号:" + st + ",查询到对应的商品为:" + tm.get(st));
} else {
System.out.println("查无此商品");
}
}
}
|
|