java基础 数组 Set Map 集合综合应用 生成带0的随机字符串 "00000001" 水果商品号问题
package com.swift.test01; /*有四种水果(苹果,香蕉,西瓜,橘子) 1、给每种水果设定一个商品号,商品号是8个0-9的随机数,商品号码不能重复, 最小值 "00000001", 最大值 "99999999" 2、根据商品号查询对应的商品。 如果查不到输出:“查无此商品” 如果能查到打印:”根据商品号:12345678,查询到对应的商品为:西瓜”*/ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; public class ShuiguoMap { public static void main(String[] args) { String[] fruits = new String[] { "苹果", "香蕉", "西瓜", "橘子" }; Set<String> nums = new HashSet<String>(); getNums(nums); Map<String, String> map = new HashMap<>(); int i = 0; for (String str : nums) { map.put(str, fruits[i++]); } System.out.println(map); String strNum = "12568738"; findFuit(map, strNum); } private static void findFuit(Map<String, String> map, String strNum) { if (!map.containsKey(strNum)) { System.out.println("经查,无此商品."); } else { System.out.println("根据商品号" + strNum + "查询到对应的商品" + map.get(strNum)); } } private static void getNums(Set<String> nums) { Random ran = new Random(); while (nums.size() < 4) { String str = ""; for (int i = 0; i < 8; i++) { int n = ran.nextInt(10); str = str + n; } nums.add(str); } System.out.println(nums); } }
Never waste time any more, Never old man be a yong man