有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java迭代器在找到匹配项后中途停止

//Example from class that I was trying to base off of:

public void printMajors(String major) {
for(Student x : dir) {

//dir = new HashMap<Integer, Student>(); and Student is the second class.

if (x.getMajor().equals(major)) {
System.out.println(x.getName());
    }
}

}

我想打印出所有插入了相同区号的人,但迭代器在找到匹配项后中途停止。我如何让它继续循环并打印出每个人的区号相同

//代码中的问题

public boolean printAreaCode(String areacode) {
    for (String p : phonebook.values()) {
        if (p.startsWith(areacode)) {
            for (String name : phonebook.keySet()) {
                String key = name;
                System.out.println(key);
                return true;
            }
        }
    }
    return false;
}

整个任务

import java.util.HashMap;
import java.util.Iterator;

public class PhoneBook {

    private HashMap<String, String> phonebook;

    public static void main(String[] args) {
    PhoneBook phone = new PhoneBook();
    phone.addEntry("Alexander Schnell", "987-654-3210");
    phone.addEntry("Bob the Builder", "555-555-5555");
    phone.addEntry("Michael", "465-858-5555");
    phone.addEntry("Robert", "778-555-1234");
    phone.addEntry("Charlie", "987-546-4564");
    phone.addEntry("Steve", "909-555-7845");
    System.out.println("All of the people in the directory:");
    phone.printListings(); //works
    System.out.println("");
    System.out.println("People with matching area codes:"); //WIP
    phone.printAreaCode("987");
    System.out.println("");
    System.out.println("Prints phone number for requested person:");
    phone.getNumber("Bob the Builder"); //works
}
//Adds a new entry to the phone book (naturally).
//It has two parameters, both Strings: the person’s name and their phone
//number (in the form “610-499-4035”).

public void addEntry(String name, String number) {
    phonebook.put(name, number);
}
//prints the names and phone numbers of everyone in the phone book

private void printListings() {
    for (Iterator<String> it = phonebook.keySet().iterator(); it.hasNext();) {
        for (String p : phonebook.values()) {
            String key = (String) it.next();
            System.out.println(key + ": " + p.toString());
        }
    }
}
//looks up a number in the map.
//It has one parameter (a person’s name) and returns a PhoneNumber object.

public String getNumber(String name) {
    //public void getNumber(String name) {
    // no return statement
    System.out.println(phonebook.get(name));
    return phonebook.get(name);
}
//prints the names of all people with the given area code

public boolean printAreaCode(String areacode) {
    for (String p : phonebook.values()) {
        if (p.startsWith(areacode)) {
            for (String name : phonebook.keySet()) {
                String key = name;
                System.out.println(key);
                return true;
            }
        }
    }
    return false;
    }

    public PhoneBook() {
        phonebook = new HashMap<String, String>();
    }
}

我甚至不认为这门课能和我的主课交流。 我的老师刚才说必须包括在内。 这可能是个问题

public class PhoneNumber {
    private String areacode;
    private String prefix;
    private String four;

    //Insert a phone number
    public PhoneNumber(String number) {
        String[] parts = number.split("-");
        areacode = parts[0];
        prefix = parts[1];
        four = parts[2];
    }

    @Override
    public String toString() {
        String s = areacode + "-" + prefix + "-" + four;
        return s;
    }
}

共 (4) 个答案

  1. # 1 楼答案

    您在地图中的迭代错误您的return true;语句是问题的原因,但我们暂时忽略这一点

    总是像这样迭代地图:

    for(Map.Entry<String, String> entry: phoneBook.entrySet())
    {
        if(entry.getValue().startsWith(areaCode))
        {
            System.out.println(entry.getKey());
        }
    } 
    
  2. # 2 楼答案

    所以,你需要打印keyvaluestartsWith{},所以你的代码基本上是向后的

    目前,您可以通过代码扫描来寻找匹配的值,这是可以的,但它会打印所有key值吗

    相反,您需要从每个key开始,获取value,然后测试与键关联的value是否与areacode匹配

    public boolean printAreaCode(String areacode) {
        boolean found = false;
        for (String key : phonebook.keySet()) {
            String value = phonebook.get(key);
            if (value.startsWith(areacode)) {
                System.out.println(key);
                found = true;
            }
        }
        return found;
    }
    

    现在,这是非常低效的。基本上,对于每个迭代,您都要求Map查找与key关联的值,这需要Map搜索它的所有不同条目/节点,试图找到匹配的键。虽然在你的例子中,这可能不是一个巨大的延迟,但确实应该尽可能避免

    相反,Map提供了对Entry的访问,它将keyvalue配对成一个对象,使其访问速度更快,例如

    public boolean printAreaCode(String areacode) {
        boolean found = false;
        for (Map.Entry<String, String> entry : phonebook.entrySet()) {
            String value = entry.getValue();
            if (value.startsWith(areacode)) {
                String key = entry.getKey();
                System.out.println(key);
                found = true;
            }
        }
        return found;
    }
    

    现在,HashMapMap的一个实现,所以通常我更喜欢使用

    private Map<String, String> phonebook;
    

    而不是

    private HashMap<String, String> phonebook;
    

    除非我对某些只在HashMap中定义的功能有特殊需求,否则may code不会在意我以后是否使用TreeMap

  3. # 3 楼答案

    你不能加这一行import java.util.Map;

    我很好奇为什么你不能添加import语句;这是标准的一部分还是你不知道怎么做

    你必须在地图上迭代两次。是的,这是非常低效的代码

    public boolean printAreaCode(String areacode) {
    boolean haveMatch = false;
    for (String p : phonebook.values()) {
        if (p.startsWith(areacode)) {
            String value = p;
            for (String name : phonebook.keySet()) {
                if(value.equals(phonebook.get(name)) {
                    System.out.println(key);
                    haveMatch = true;
            }
        }
    }
    return haveMatch;
    

    }

  4. # 4 楼答案

    我相信你的目的是打印电话号码,其中代码以某个值开头。因此,我们不必从该方法返回任何内容,您可以将返回类型设置为void。你可以让它类似于你的printListings

    public void printAreaCode(String areacode) {
        for (String p : phonebook.values()) {
            if (p.startsWith(areacode)) {
                for (String name : phonebook.keySet()) {
                    String key = name;
                    System.out.println(key);
    
                }
            }
        }
    
        }