Java程序设计给定n本书的名称和定价,本题要求编写程序,查找并输出其中定价最高和最低的书的名称和定价。
时间: 2024-06-03 21:06:15 浏览: 139
您好,对于这个问题,您可以先定义一个Book类,包含书名和定价两个属性。然后再创建一个BookStore类,包含一个Book类型的数组,存储书籍信息。接下来,遍历数组,比较每一本书的价格,找到最高和最低的价格,并记录对应的书名。最后输出即可。
以下是Java代码示例:
```java
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
class BookStore {
private Book[] books;
public BookStore(Book[] books) {
this.books = books;
}
public void findMaxAndMinPrice() {
double maxPrice = Double.MIN_VALUE;
double minPrice = Double.MAX_VALUE;
String maxName = "";
String minName = "";
for (Book book : books) {
if (book.getPrice() > maxPrice) {
maxPrice = book.getPrice();
maxName = book.getName();
}
if (book.getPrice() < minPrice) {
minPrice = book.getPrice();
minName = book.getName();
}
}
System.out.println("最高价书籍名称:" + maxName + ",价格:" + maxPrice);
System.out.println("最低价书籍名称:" + minName + ",价格:" + minPrice);
}
}
public class Main {
public static void main(String[] args) {
Book[] books = new Book;
books = new Book("Java编程思想", 89.8);
books = new Book("Java核心技术", 78.5);
books = new Book("Java从入门到精通", 68.9);
BookStore bookStore = new BookStore(books);
bookStore.findMaxAndMinPrice();
}
}
```
希望能够对您有所帮助。
阅读全文