java - 使用给定的字符串参数搜索数组元素

标签 java arrays sorting methods collections

我正在尝试为我的 BookCollection 类编写一个 findBook 方法。它查找具有指定 ISBN 的书籍。我无法找到比较不同类型元素的方法。我们得到了这个方法:

public void changePrice(String isbn, double price){
    int index = findBook(isbn);                                                //CREATE FINDBOOK METHOD TO HELP THIS METHOD
    if( index == -1){
        throw new UnsupportedOperationException("BookNotFound");
    }
    collection[index].setPrice(price); 
}

但是我很困惑为什么要将整数索引与带有字符串参数的 findbook 方法进行比较。基本上,我们有一个 Book[] 类型的集合,并且使用给定的参数 isbn,必须在该图书集合中搜索该 isbn。

这是我迄今为止所掌握的内容的粗略估计:

   //this method is a helper function
   private String findBook(int is){
      this.isbn = is;   
      for(int i = 0; i <= collection.length; i++){
         add(isbn);
      }  
   } 

我知道这个方法是错误的,但我在想如何写这个方法时遇到了很多麻烦。如何使用字符串参数 isbn 搜索 Book[] 类型的集合?如果你们想要我的完整代码,请告诉我,我会发布它!

感谢所有提供帮助的人!

@drorbs 这是我的数据字段和构造函数:

  private int limit = 200;
   //Array of type book
   private int Book[];

   //actual size of collection, initialized to zero. Must never exceed limit
   private Book[] collection;    //collection is of book type    

   private int lastElement;

   //Constructor
   public BookCollection(int l){
      limit = l;
      int lastElement = 0;
         if(limit <= 200){
            Book[] collection = new Book[limit];
         } else{
            throw new UnsupportedOperationException("CannotExceedLimit");
           }   
      }

最佳答案

这种方法的简单实现是:

private int findBook(String isbn){
    // iterate all the Book elements in the collection array
    for(int i = 0; i <= collection.length; i++){
        // check if the current book isbn matches the one provided argument
        if (collection[i].getIsbn().equals(isbn))
            return i;
    }
    return -1;
}

请注意,如果您正在查找图书索引,则方法返回类型应为 int,并且 isbn 参数应为 String 类型。
此外,我认为 bookscollection 更适合该数组的名称。

关于java - 使用给定的字符串参数搜索数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965801/

相关文章:

algorithm - 不同排序算法的空间复杂度差异

Java Jframe,需要先切换窗 Eloquent 能使用控件

python - 如何对 numpy 数组进行 n 维距离和最近邻计算

jquery - 通过交替点击对 JSON Z-A 进行排序

python - 如何以这种特定方式连接两个数组

arrays - Perl 中的多维数组或散列。访问项目

javascript - 根据具有不同数据类型的两个键按升序对对象数组进行排序

java - 类路径问题,head first servlets book

java - 同一模块的 Gradle 编译错误

java - 防止 Glassfish 使用自己的库版本而不是项目中的库