日期:2014-05-19 浏览次数:20698 次
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Map.Entry; public class Book { /** * 第二题 */ private String name;// 书名 private int page;// 页数 public Book(String name, int page) {// 有参构造 super(); this.name = name; this.page = page; } public String getName() {// setter getter方法 return name; } public void setName(String name) { this.name = name; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public static Map<String, Book> map = new HashMap<String, Book>(); public void initMap() { map.put("SA001", new Book("SOFT_A", 1));// 初始化 map.put("SA002", new Book("SOFT_B", 3)); map.put("SA003", new Book("SOFT_C", 5)); map.put("SA004", new Book("SOFT_D", 7)); map.put("SA005", new Book("SOFT_E", 9)); map.put("SA006", new Book("SOFT_F", 11)); map.put("SA007", new Book("SOFT_G", 13)); map.put("SA008", new Book("SOFT_H", 15)); map.put("SA009", new Book("SOFT_I", 17)); map.put("SA010", new Book("SOFT_J", 19)); } public static void printAllBookInf() { System.out.println("编号\t书名\t页数"); Set<Entry<String, Book>> set = map.entrySet(); for (Iterator iterator = set.iterator(); iterator.hasNext();) {// 迭代输出对象 Entry<String, Book> entry = (Entry<String, Book>) iterator.next(); System.out.println(entry.getKey() + "\t" + entry.getValue().getName() + "\t" + entry.getValue().getPage()); }// 打印出所有图书信息 } public static void printOneBookInf() { Random ran = new Random(); int i = ran.nextInt(10) + 1;// 随机产生书号 String str = String.valueOf(i); String id = "SA0" + str; System.out.println("该编号对应的书名:" + map.get(id).getName() + " 页数为:" + map.get(id).getPage()); }// 打印随机产生书号的信息 public static void main(String[] args) { Book.printAllBookInf();// 调用打出所有图书的方法 Book.printOneBookInf();// 调用打出随机产生图书的方法 } }
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; public class Book { /** * 第二题 */ private String name;// 书名 private int page;// 页数 public Book(String name, int page) {// 有参构造 super(); this.name = name; this.page = page; } public String getName() {// setter getter方法 return name; } public void setName(String name) { this.name = name; } public int getPage() { return page; } public void setPage(int page) {