Advertisement
Josif_tepe

Untitled

Nov 6th, 2024
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. import java.util.Scanner;
  2. public class Zadaca {
  3.  
  4.     public static void main(String[] args) {
  5.         Scanner sc = new Scanner(System.in);
  6.         System.out.println("Enter details for 3 books: ");
  7.  
  8.         Library library = new Library(3);
  9.         for(int i = 0; i < 3; i++) {
  10.             System.out.println("Enter title: ");
  11.             String title = sc.nextLine();
  12.             System.out.println("Enter author: ");
  13.             String author = sc.nextLine();
  14.             System.out.println("Enter price: ");
  15.             double price = Double.parseDouble(sc.nextLine());
  16.  
  17.             Book book = new Book(title, author, price);
  18.             library.addBook(book);
  19.         }
  20.         library.displayAllBooks();
  21.     }
  22.    
  23. }
  24.  
  25. class Book {
  26.     String title;
  27.     String author;
  28.     double price;
  29.  
  30.     public Book(String title, String author, double price) {
  31.         this.title = title;
  32.         this.author = author;
  33.         this.price = price;
  34.     }
  35.  
  36.     public void print() {
  37.         System.out.println("Title: " + title);
  38.         System.out.println("Author: " + author);
  39.         System.out.println("Price: " + price);
  40.     }
  41. }
  42. class Library {
  43.     Book[] books;
  44.     int at;
  45.     public Library(int n) {
  46.         books = new Book[n];
  47.         at = 0;
  48.     }
  49.  
  50.     public void addBook(Book book) {
  51.         books[at] = book;
  52.         at++;  
  53.     }
  54.  
  55.     public void displayAllBooks() {
  56.         for(int i = 0; i < at; i++) {
  57.             books[i].print();
  58.         }
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement