输入一个英文名,如果它存在,则返回它对应的中文名和姓名。
1、定义一个学生类,属性有姓名和性别。
package day14;
public class Student{
private String name;
private String sex;
public Student() {
super();
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "姓名:" + name + ",性别:" + sex;
}
}
2、测试类
以Map键值对的方式存放。key为英文名,value为一个Student类型的对象。
package day14;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class TestStudent{
public static void main(String[] args) {
Student s1 = new Student("李雷","男");
Student s2 = new Student("小美","女");
Student s3 = new Student("汤姆","男");
Map<String,Student> map = new HashMap<String,Student>();
map.put("lilei", s1);
map.put("xiaomei", s2);
map.put("tom", s3);
System.out.println("请输入一个英文名(lilei、xiaomei、tom):");
Scanner input = new Scanner(System.in);
String username = input.next();
System.out.println("您输入的英文名"+username+"对应的信息如下:"+map.get(username));
}
}
运行结果如下:
请输入一个英文名(lilei、xiaomei、tom):
xiaomei
您输入的英文名xiaomei对应的信息如下:姓名:小美,性别:女