ArrayList打印多次

时间:2018-05-23 00:40:29

标签: java hashmap

我的问题是,当我运行此代码时,ArrayList中的所有内容都会打印大约3次。

以下是您需要查看的代码:

static ArrayList<String> list = new ArrayList<String>();
static HashMap<String, Character> books = new HashMap<String, 
Character>();

public static void main(String[] args){
//      Title, Section
books.put("Harry Potter and the blank blank blank", 'A');
books.put("Harry Potter and the blank", 'Z');
books.put("Harry Potter ", 'Z');
books.put("Harry Potter and the blank blank", 'L');
findBook("Harry");
}

public static void findBook(String title){
list.clear();
for (String key : books.keySet()) {
  if(key.equalsIgnoreCase(title)){
    System.out.println(books.get(key));
  }
  else if (key.startsWith(title)) {
    list.add(key);
  }else System.out.println("Book not found");
    for(String bookTitle : list){
      System.out.println("Book: " + bookTitle);
  }
}

请帮忙,非常感谢你! -S1ant

2 个答案:

答案 0 :(得分:0)

您保留了for循环,可以在找到的书籍中打印书籍,因此您可以获得多个打印件。移动打印出该循环的for循环,如下所示:

static ArrayList<String> list = new ArrayList<String>();
static HashMap<String, Character> books = new HashMap<String, 
Character>();

public static void main(String[] args){
//      Title, Section
books.put("Harry Potter and the blank blank blank", 'A');
books.put("Harry Potter and the blank", 'Z');
books.put("Harry Potter ", 'Z');
books.put("Harry Potter and the blank blank", 'L');
findBook("Harry");
}

public static void findBook(String title){
list.clear();
for (String key : books.keySet()) {
  if(key.equalsIgnoreCase(title)){
    System.out.println(books.get(key));
  }
  else if (key.startsWith(title)) {
    list.add(key);
  }else 
    System.out.println("Book not found");
  }
}

// Move this out of the above loop
for(String bookTitle : list){
  System.out.println("Book: " + bookTitle);

答案 1 :(得分:0)

每次尝试查找图书时都会执行以下for循环。因此,您会看到多个打印件。

for (String bookTitle : list) {
    System.out.println("Book: " + bookTitle);
}

您可以将上面的for循环移动到main方法中,并在findBook方法调用之后立即移动。