Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,如何使用类的string属性来引用该类?_Java_Oop_Object - Fatal编程技术网

在java中,如何使用类的string属性来引用该类?

在java中,如何使用类的string属性来引用该类?,java,oop,object,Java,Oop,Object,我有以下3个类,用来表示一个程序,允许用户创建一种数据库,可以添加人及其电话号码和地址,然后在创建后搜索 以下是课程: 人 import java.util.*; public class Person implements Comparable<Person> { private final String name; private String street; private String city; private String address; pub

我有以下3个类,用来表示一个程序,允许用户创建一种数据库,可以添加人及其电话号码和地址,然后在创建后搜索

以下是课程:

import java.util.*;


public class Person implements Comparable<Person> {

 private final String name;
 private String street;
 private String city;
 private String address;

    public Person(String name) {
        this.name = name;
        this.address = "address unknown";
    }

    public String getName() {
        return name;
    }

    public void setAddress(String street, String city){
        this.city = city;
        this.street = street;
        this.address = this.street + " " + this.city;
    }

    public String getAddress() {
        return address;
    }

    @Override
    public int compareTo(Person o) {
        return this.name.compareToIgnoreCase(o.getName());
    }











}
我对UI中的代码有一个问题

else if(command == 2){
                System.out.print("whose number: ");
                String person = reader.nextLine();

当命令以2形式给出时,我要求用户提供一个名称,该名称以字符串形式给出,然后如何使用该字符串在HashMap下找到具有该名称的person对象的值,即与person关联的一组数字

显然,我不能用映射上的get方法来实现这一点,因为键是person对象而不是字符串,我不知道该怎么做(我是否需要在字符串名和人名之间存储映射),我相信在这个上下文中,名称是唯一的

还有一个额外的问题:当我执行命令1并给出一个不全是数字的数字(例如“045-4558”)时,为什么会出现错误


谢谢

也许是这样的:

for (Map.Entry<Person, Set<String>> entry : numbers.entrySet()) {
    Person key = entry.getKey();

    if (key.getName().equals(nameWhichYouAreLookingFor)) {
       //Do whatever you want
    }
}
for(Map.Entry:numbers.entrySet()){
Person key=entry.getKey();
if(key.getName().equals(您正在查找的名称)){
//你想干什么就干什么
}
}

但是Java中的字符串对象。额外的问题回答:您使用
Integer.parseInt()
。它将字符串解析为其等效整数
045-4558
没有等效的整数。请在
PhoneNumber
中添加一个方法以按姓名搜索
人员:
public Person searchByName(String name){/*todo*/}
您无法比较这样的字符串。使用
equals()
else if(command == 2){
                System.out.print("whose number: ");
                String person = reader.nextLine();

for (Map.Entry<Person, Set<String>> entry : numbers.entrySet()) {
    Person key = entry.getKey();

    if (key.getName().equals(nameWhichYouAreLookingFor)) {
       //Do whatever you want
    }
}