通过使用Map存储用户和其对应的电话号码,并实现简单的增、删、查、改。
一、具体实现
代码如下:
package demo_map;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Work_1 {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);//创建键盘输入扫描
Map<String,Long> map = new HashMap<String,Long>();//创建一个map用来存储输入的用户名和其对应的电话
while(true){
menu();
System.out.print("请输入选择:");
int choice = input.nextInt();
switch (choice) {
case 1:input(map);break;//添加用户信息
case 2:show(map);break;//查看所有用户信息
case 3:select(map);break;//查询某个用户信息
case 4:delet(map);break;//删除某个用户
case 5:System.out.println("已退出!!!");return;
default:
System.out.println("输入选项不存在!!!请重新输入!!!");
break;
}
}
}
private static void delet(Map<String, Long> map) {
// TODO Auto-generated method stub
System.out.print("请输入用户名:");
String key = input.next();//需要查看信息的用户名
if(map.containsKey(key)){
System.out.print("是否删除名为" + key + "的用户信息(y/n):");
while(true){
String isDelet = input.next();
if(isDelet.equalsIgnoreCase("y")){
map.remove(key);
System.out.println("删除成功!!!");
break;
}else if(isDelet.contentEquals("n")){
System.out.println("删除失败!!!");
break;
}else{
System.out.println("输入错误,请重新输入!!!");
}
}
}else{
System.out.println("不存在此用户名!!!");
}
}
private static void select(Map<String, Long> map) {
// TODO Auto-generated method stub
System.out.print("请输入用户名:");
String key = input.next();//需要查看信息的用户名
if(map.containsKey(key)){
System.out.println(key + "的用户信息如下:");
System.out.println("用户名:\t" + key);
System.out.println("电话:\t" + map.get(key));
}else{
System.out.println("不存在此用户名!!!");
}
}
private static void show(Map<String, Long> map) {
// TODO Auto-generated method stub
System.out.println("用户名\t电话");
for (Map.Entry<String,Long> entry : map.entrySet()) {
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
private static void input(Map<String, Long> map) {
while(true){
//输入用户名
System.out.print("请输入用户名:");
String userName = input.next();
//输入电话
System.out.print("请输入" + userName + "的电话:");
Long number = input.nextLong();
//插入用户名信息
map.put(userName, number);
System.out.print("按任意键继续,是否继续(y/n):");
String isInput = input.next();
if(isInput.equalsIgnoreCase("n")) break;
}
}
private static void menu() {
// TODO Auto-generated method stub
System.out.println("*************************************");
System.out.println("1.录入用户信息\n2.查看所有用户信息\n3.查询用户信息\n4.删除用户\n5.退出");
System.out.println("*************************************");
}
}
二、测试
1.录入测试
2.查看所有用户信息
3.查询用户信息