有三個class,很簡單。記住Map類是以鍵值對存在的方式便可,比List類確實簡單了一些。java
(實現的功能:代替數組進行數據的增刪改查)數組
代碼貼上this
package demo5;spa
public class Monkey {rem
private String num;get
private String name;input
public Monkey(String num, String name) {it
super();io
this.num = num;class
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package demo5;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MonkeyManager {
Map hm=null;
public MonkeyManager() {
super();
hm=new HashMap();
}
//查找猴子
public void Showfind(String num){
if(hm.containsKey(num)){
System.out.print("猴子的編號是:"+((Monkey)hm.get(num)).getNum()+"\t猴子的名字是:"+((Monkey)hm.get(num)).getName());
}
else
System.out.println("沒有這個猴子的信息");
}
//添加猴子
public void addMonkey(Monkey monkey){
hm.put(monkey.getNum(),monkey);
System.out.println("增長成功:");
}
//替換猴子,按編號來替換猴子的名字
public void changeMonkey(String num,Monkey monkey){
if(hm.containsKey(num))
{
hm.remove(num);
hm.put(monkey.getNum(),monkey);
System.out.println("替換成功:");
}
else
{System.out.println("沒有這個猴子");}
}
//顯示全部猴子的信息
public void showInfo(){
Iterator it=hm.keySet().iterator();
while(it.hasNext())
{
String key=it.next().toString();
System.out.print(" 猴子的編號是:"+((Monkey)hm.get(key)).getNum()+"\t猴子的名字是:"+((Monkey)hm.get(key)).getName());
}
}
//猴子的刪除
public void delMonkey(String num){
if(hm.containsKey(num))
{
hm.remove(num);
System.out.println("刪除成功");}
else
System.out.println("沒有這個猴子,刪除失敗");
}
}
package demo5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
MonkeyManager manager=new MonkeyManager();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{System.out.println("\n請輸入你要操做的數字:");
System.out.println("1=添加猴子");
System.out.println("2=查找猴子");
System.out.println("3=替換猴子");
System.out.println("4=顯示全部猴子的信息");
System.out.println("5=刪除猴子");
System.out.println("6=退出操做");
String input=br.readLine();
if(input.equals("1"))
{
System.out.print("請輸入編號:");
String bianhao=br.readLine();
System.out.print("請輸入名字:");
String name=br.readLine();
Monkey monkey =new Monkey(bianhao,name);
manager.addMonkey(monkey);
}
else if(input.equals("2"))
{
System.out.print("請輸入你要查找猴子的編號:");
String bianhao=br.readLine();
manager.Showfind(bianhao);
}
else if(input.equals("3"))
{
System.out.print("請輸入你要替換猴子的編號:");
String bianhao=br.readLine();
System.out.print("請輸入你要猴子的新名字:");
String name=br.readLine();
Monkey monkey =new Monkey(bianhao,name);
manager.changeMonkey(bianhao,monkey);
}
else if(input.equals("4"))
{
manager.showInfo();
}
else if(input.equals("5"))
{
System.out.println("請輸入你要刪除的猴子的編號:");
String bianhao=br.readLine();
manager.delMonkey(bianhao);
}
else if(input.equals("6"))
{
System.err.println("退出成功");
}
}
}
}