Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Zadaca {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter details for 3 books: ");
- Library library = new Library(3);
- for(int i = 0; i < 3; i++) {
- System.out.println("Enter title: ");
- String title = sc.nextLine();
- System.out.println("Enter author: ");
- String author = sc.nextLine();
- System.out.println("Enter price: ");
- double price = Double.parseDouble(sc.nextLine());
- Book book = new Book(title, author, price);
- library.addBook(book);
- }
- library.displayAllBooks();
- System.out.println("Enter author: ");
- String matchingAuthor = sc.nextLine();
- library.findBooksByAuthor(matchingAuthor);
- library.displayAllBooks();
- library.sortBooksByPrice();
- library.displayAllBooks();
- }
- }
- class Book {
- String title;
- String author;
- double price;
- public Book(String title, String author, double price) {
- this.title = title;
- this.author = author;
- this.price = price;
- }
- public String getAuthor() {
- return author;
- }
- public double getPrice() {
- return price;
- }
- public void print() {
- System.out.println("Title: " + title);
- System.out.println("Author: " + author);
- System.out.println("Price: " + price);
- }
- }
- class Library {
- Book[] books;
- int at;
- public Library(int n) {
- books = new Book[n];
- at = 0;
- }
- public void addBook(Book book) {
- books[at] = book;
- at++;
- }
- public void displayAllBooks() {
- for(int i = 0; i < at; i++) {
- books[i].print();
- }
- }
- public void findBooksByAuthor(String author) {
- for(int i = 0; i < at; i++) {
- if(books[i].getAuthor() == author) {
- books[i].print();
- }
- }
- }
- public void sortBooksByPrice() {
- for(int i = 0; i < at; i++){
- for(int j = i + 1; j < at; j++) {
- if(books[i].getPrice() > books[j].getPrice()) {
- Book tmp = books[i];
- books[i] = books[j];
- books[j] = tmp;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement