gpt4 book ai didi

java - ArrayList 从文件中读取行并分配它们

转载 作者:行者123 更新时间:2023-12-02 01:47:57 24 4
gpt4 key购买 nike

我创建了一个从文件中读取的代码,每一行都是一本不同的书,每一行都包含一个标题和价格。书籍文件是:

    The Hobbit,$15.00
Purple Cow,$10.00
Death by Black Hole,$35.00

这些方法有效。但我正在尝试创建一种方法,其工作原理如下:输入预算:15,然后显示 15 美元以下的所有书籍。我已经完成了 searchForPrice 方法的一部分,但它并没有真正发挥作用。我怎样才能做到呢?谢谢。

import java.util.*;
import java.io.*;
import javax.swing.*;
public class BookStore {
private ArrayList<Book> library;
String Book;

public BookStore() throws FileNotFoundException {
library = readBooks("books1.txt");
}
public ArrayList<Book> readBooks(String path) {
ArrayList<Book> books = new ArrayList<Book>();

try{
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
String[] arr = line.split(",");
String title = arr[0];
double price = Double.parseDouble(arr[1].trim().replace("$",""));//in case has a $
books.add(new Book(title,price));

}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
return books;
}

public String toString() {
String result = "";
for (Book tempBook : library) {
result += tempBook.toString() + "\n";
}
return result;
}

public ArrayList<Book> searchForTitle(String searchString) {
ArrayList<Book> searchResult = new ArrayList<Book>();
for (Book currentBook : library) {
if ((currentBook.getTitle()).indexOf(searchString) != -1)
searchResult.add(currentBook);
}
searchResult.trimToSize();
return searchResult;
}

//get lowest price book
public Book lowestPrice() {
Book lowestPrice = library.get(0);
for (Book book : library) {
if (book.getPrice() < lowestPrice.getPrice()) {
lowestPrice = book;
}
}
return lowestPrice;
}

//bookslessthanthenumbertheyenter
public ArrayList<Book> searchForPrice(double searchdouble) {
ArrayList<Book> searchPrice = new ArrayList<Book>();
for (Book currentBook : library) {
if ((currentBook.getPrice()).Double.parseDouble.indexOf(searchdouble) != -1)
searchPrice.add(currentBook);
}
searchPrice.trimToSize();
return searchPrice;
}
}

最佳答案

这个循环是否编译:

for (Book currentBook : library) {
if ((currentBook.getPrice()).Double.parseDouble.indexOf(searchdouble) != -1)
searchPrice.add(currentBook);
}

Book类中,您将价格存储为double,因此不需要转换,只需将每本书的价格与searchdouble进行比较即可:

for (Book currentBook : library) {
if (currentBook.getPrice() < searchdouble)
searchPrice.add(currentBook);
}

还有为什么你需要:

searchPrice.trimToSize();

因为您没有声明任何初始容量?

关于java - ArrayList 从文件中读取行并分配它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462769/

24 4 0