Java

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 15

Sure, here's a Java exercise that involves three classes and uses getters and

setters to work with tables. In this exercise, we'll create a simple representation
of a library system with three classes: Library, Book, and Member. The Library
class will manage books and members, while the Book and Member classes will
represent individual books and library members. Each class will have getters and
setters to access and modify their properties.

import java.util.ArrayList;
import java.util.List;

class Book {
private String title;
private String author;
private int year;

public Book(String title, String author, int year) {


this.title = title;
this.author = author;
this.year = year;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public int getYear() {


return year;
}

public void setYear(int year) {


this.year = year;
}
}

class Member {
private String name;
private int memberId;

public Member(String name, int memberId) {


this.name = name;
this.memberId = memberId;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}

public int getMemberId() {


return memberId;
}

public void setMemberId(int memberId) {


this.memberId = memberId;
}
}

class Library {
private List<Book> books;
private List<Member> members;

public Library() {
books = new ArrayList<>();
members = new ArrayList<>();
}

public void addBook(Book book) {


books.add(book);
}

public void removeBook(Book book) {


books.remove(book);
}

public void addMember(Member member) {


members.add(member);
}

public void removeMember(Member member) {


members.remove(member);
}

public List<Book> getBooks() {


return books;
}

public List<Member> getMembers() {


return members;
}
}

public class Main {


public static void main(String[] args) {
// Create a library
Library library = new Library();

// Create books and members


Book book1 = new Book("Java Programming", "John Doe", 2020);
Book book2 = new Book("Python Basics", "Jane Smith", 2019);
Member member1 = new Member("Alice", 1);
Member member2 = new Member("Bob", 2);

// Add books and members to the library


library.addBook(book1);
library.addBook(book2);
library.addMember(member1);
library.addMember(member2);

// Retrieve and display the library's books and members


List<Book> libraryBooks = library.getBooks();
List<Member> libraryMembers = library.getMembers();

System.out.println("Library Books:");
for (Book book : libraryBooks) {
System.out.println("Title: " + book.getTitle() + ", Author: " +
book.getAuthor() + ", Year: " + book.getYear());
}

System.out.println("\nLibrary Members:");
for (Member member : libraryMembers) {
System.out.println("Name: " + member.getName() + ", Member ID: " +
member.getMemberId());
}
}
}
In this exercise, you have a Book class with getters and setters for title, author,
and year, a Member class with getters and setters for name and member ID, and a
Library class that allows you to add and remove books and members while providing
access to the lists of books and members through getters. The Main class
demonstrates how to use these classes by creating a library, adding books and
members, and displaying their information.

User
use now sort by name
ChatGPT
To sort the library's books and members by name, you can modify the Library class
to provide sorting methods. Here's an updated version of the Library class that
includes sorting methods by name for both books and members:

java
Copy code
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Library {
private List<Book> books;
private List<Member> members;

public Library() {
books = new ArrayList<>();
members = new ArrayList<>();
}

public void addBook(Book book) {


books.add(book);
}
public void removeBook(Book book) {
books.remove(book);
}

public void addMember(Member member) {


members.add(member);
}

public void removeMember(Member member) {


members.remove(member);
}

public List<Book> getBooks() {


return books;
}

public List<Member> getMembers() {


return members;
}

public void sortBooksByName() {


Collections.sort(books, Comparator.comparing(Book::getTitle));
}

public void sortMembersByName() {


Collections.sort(members, Comparator.comparing(Member::getName));
}
}
Now, you can sort the books and members by name using the sortBooksByName() and
sortMembersByName() methods. Here's how you can use these sorting methods in the
Main class:

java
Copy code
public class Main {
public static void main(String[] args) {
// Create a library
Library library = new Library();

// Create books and members


Book book1 = new Book("Java Programming", "John Doe", 2020);
Book book2 = new Book("Python Basics", "Jane Smith", 2019);
Member member1 = new Member("Alice", 1);
Member member2 = new Member("Bob", 2);

// Add books and members to the library


library.addBook(book1);
library.addBook(book2);
library.addMember(member1);
library.addMember(member2);

// Sort books and members by name


library.sortBooksByName();
library.sortMembersByName();

// Retrieve and display the library's books and members


List<Book> libraryBooks = library.getBooks();
List<Member> libraryMembers = library.getMembers();
System.out.println("Library Books (Sorted by Name):");
for (Book book : libraryBooks) {
System.out.println("Title: " + book.getTitle() + ", Author: " +
book.getAuthor() + ", Year: " + book.getYear());
}

System.out.println("\nLibrary Members (Sorted by Name):");


for (Member member : libraryMembers) {
System.out.println("Name: " + member.getName() + ", Member ID: " +
member.getMemberId());
}
}
}
In this updated code, the sortBooksByName() and sortMembersByName() methods sort
the books and members by name, and then you can display the sorted lists in the
Main class.

User
use heritage
ChatGPT
Sure, let's introduce inheritance (heritage in some regions) to our classes. In
this modified version, we'll create a common base class LibraryItem that both Book
and Member classes will inherit from. This base class will contain common
properties such as a name/title for items in the library. Then, we'll use
inheritance to demonstrate how you can use this approach to simplify the code.

Here's the updated code:

java
Copy code
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class LibraryItem {
private String name;

public LibraryItem(String name) {


this.name = name;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

class Book extends LibraryItem {


private String author;
private int year;

public Book(String title, String author, int year) {


super(title);
this.author = author;
this.year = year;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public int getYear() {


return year;
}

public void setYear(int year) {


this.year = year;
}
}

class Member extends LibraryItem {


private int memberId;

public Member(String name, int memberId) {


super(name);
this.memberId = memberId;
}

public int getMemberId() {


return memberId;
}

public void setMemberId(int memberId) {


this.memberId = memberId;
}
}

class Library {
private List<Book> books;
private List<Member> members;

public Library() {
books = new ArrayList<>();
members = new ArrayList<>();
}

public void addBook(Book book) {


books.add(book);
}

public void removeBook(Book book) {


books.remove(book);
}

public void addMember(Member member) {


members.add(member);
}
public void removeMember(Member member) {
members.remove(member);
}

public List<Book> getBooks() {


return books;
}

public List<Member> getMembers() {


return members;
}

public void sortItemsByName(List<? extends LibraryItem> items) {


Collections.sort(items, Comparator.comparing(LibraryItem::getName));
}
}

public class Main {


public static void main(String[] args) {
// Create a library
Library library = new Library();

// Create books and members


Book book1 = new Book("Java Programming", "John Doe", 2020);
Book book2 = new Book("Python Basics", "Jane Smith", 2019);
Member member1 = new Member("Alice", 1);
Member member2 = new Member("Bob", 2);

// Add books and members to the library


library.addBook(book1);
library.addBook(book2);
library.addMember(member1);
library.addMember(member2);

// Sort books and members by name using the common method


library.sortItemsByName(library.getBooks());
library.sortItemsByName(library.getMembers());

// Retrieve and display the library's books and members


List<Book> libraryBooks = library.getBooks();
List<Member> libraryMembers = library.getMembers();

System.out.println("Library Books (Sorted by Name):");


for (Book book : libraryBooks) {
System.out.println("Title: " + book.getName() + ", Author: " +
book.getAuthor() + ", Year: " + book.getYear());
}

System.out.println("\nLibrary Members (Sorted by Name):");


for (Member member : libraryMembers) {
System.out.println("Name: " + member.getName() + ", Member ID: " +
member.getMemberId());
}
}
}
In this updated code, the LibraryItem class serves as a common base class for both
Book and Member, providing the name property, which is inherited by these classes.
The Library class now has a sortItemsByName method that can sort any list of items
inheriting from LibraryItem by name. This simplifies the sorting process and
demonstrates the use of inheritance in a library management system.

User
make try and exeption for error interception
ChatGPT
To add error interception using try-catch blocks for potential exceptions, you can
modify the code to handle exceptions that may occur during operations like adding
or removing items from the library. In this example, we will handle exceptions when
trying to remove a non-existing book or member.

Here's the updated code with exception handling:

java
Copy code
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class LibraryItem {
private String name;

public LibraryItem(String name) {


this.name = name;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

class Book extends LibraryItem {


private String author;
private int year;

public Book(String title, String author, int year) {


super(title);
this.author = author;
this.year = year;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public int getYear() {


return year;
}

public void setYear(int year) {


this.year = year;
}
}

class Member extends LibraryItem {


private int memberId;

public Member(String name, int memberId) {


super(name);
this.memberId = memberId;
}

public int getMemberId() {


return memberId;
}

public void setMemberId(int memberId) {


this.memberId = memberId;
}
}

class Library {
private List<Book> books;
private List<Member> members;

public Library() {
books = new ArrayList<>();
members = new ArrayList<>();
}

public void addBook(Book book) {


books.add(book);
}

public void removeBook(Book book) {


try {
books.remove(book);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}

public void addMember(Member member) {


members.add(member);
}

public void removeMember(Member member) {


try {
members.remove(member);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}

public List<Book> getBooks() {


return books;
}

public List<Member> getMembers() {


return members;
}

public void sortItemsByName(List<? extends LibraryItem> items) {


Collections.sort(items, Comparator.comparing(LibraryItem::getName));
}
}

public class Main {


public static void main(String[] args) {
// Create a library
Library library = new Library();

// Create books and members


Book book1 = new Book("Java Programming", "John Doe", 2020);
Book book2 = new Book("Python Basics", "Jane Smith", 2019);
Member member1 = new Member("Alice", 1);
Member member2 = new Member("Bob", 2);

// Add books and members to the library


library.addBook(book1);
library.addBook(book2);
library.addMember(member1);
library.addMember(member2);

// Try to remove a book that doesn't exist


Book nonExistingBook = new Book("Non-Existent Book", "Unknown Author",
2000);
library.removeBook(nonExistingBook);

// Try to remove a member that doesn't exist


Member nonExistingMember = new Member("Unknown Member", 3);
library.removeMember(nonExistingMember);

// Sort books and members by name using the common method


library.sortItemsByName(library.getBooks());
library.sortItemsByName(library.getMembers());

// Retrieve and display the library's books and members


List<Book> libraryBooks = library.getBooks();
List<Member> libraryMembers = library.getMembers();

System.out.println("Library Books (Sorted by Name):");


for (Book book : libraryBooks) {
System.out.println("Title: " + book.getName() + ", Author: " +
book.getAuthor() + ", Year: " + book.getYear());
}

System.out.println("\nLibrary Members (Sorted by Name):");


for (Member member : libraryMembers) {
System.out.println("Name: " + member.getName() + ", Member ID: " +
member.getMemberId());
}
}
}
In this code, we've added try-catch blocks within the removeBook and removeMember
methods to handle exceptions that may occur when attempting to remove items that do
not exist in the library. It catches any exceptions and prints an error message.

User
give me another exercice and use all that i mentioned before and use arrays and
array sorts
ChatGPT
Certainly, here's another Java exercise that combines the concepts of classes,
inheritance, error interception with try-catch, arrays, and array sorting. In this
exercise, we'll create a simple student management system with three classes:
Student, Course, and StudentManager. Students can enroll in courses, and we'll
provide functionality to add, remove, and sort students within courses.

java
Copy code
import java.util.Arrays;
import java.util.Comparator;

class Student {
private String name;
private int studentId;

public Student(String name, int studentId) {


this.name = name;
this.studentId = studentId;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getStudentId() {


return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

@Override
public String toString() {
return "Student [Name: " + name + ", Student ID: " + studentId + "]";
}
}

class Course {
private String courseName;
private Student[] students;
private int studentCount;

public Course(String courseName, int maxStudents) {


this.courseName = courseName;
this.students = new Student[maxStudents];
this.studentCount = 0;
}

public String getCourseName() {


return courseName;
}

public void setCourseName(String courseName) {


this.courseName = courseName;
}

public void enrollStudent(Student student) {


if (studentCount < students.length) {
students[studentCount] = student;
studentCount++;
} else {
System.out.println("Error: The course is full. Cannot enroll more
students.");
}
}

public void removeStudent(Student student) {


for (int i = 0; i < studentCount; i++) {
if (students[i] == student) {
students[i] = null;
for (int j = i; j < studentCount - 1; j++) {
students[j] = students[j + 1];
}
students[studentCount - 1] = null;
studentCount--;
return;
}
}
System.out.println("Error: Student not found in the course.");
}

public Student[] getStudents() {


return Arrays.copyOf(students, studentCount);
}
}

class StudentManager {
public static void sortStudentsByName(Student[] students) {
Arrays.sort(students, Comparator.comparing(Student::getName));
}

public static void main(String[] args) {


// Create courses
Course mathCourse = new Course("Mathematics 101", 5);
Course historyCourse = new Course("History 101", 3);

// Create students
Student student1 = new Student("Alice", 1);
Student student2 = new Student("Bob", 2);
Student student3 = new Student("Charlie", 3);
Student student4 = new Student("David", 4);
Student student5 = new Student("Eve", 5);
// Enroll students in courses
mathCourse.enrollStudent(student1);
mathCourse.enrollStudent(student2);
mathCourse.enrollStudent(student3);
historyCourse.enrollStudent(student3);
historyCourse.enrollStudent(student4);
historyCourse.enrollStudent(student5);

// Sort students in the history course by name


Student[] historyStudents = historyCourse.getStudents();
sortStudentsByName(historyStudents);

System.out.println("Math Course Students:");


for (Student student : mathCourse.getStudents()) {
System.out.println(student);
}

System.out.println("\nHistory Course Students (Sorted by Name):");


for (Student student : historyStudents) {
System.out.println(student);
}
}
}
In this exercise, we have three classes: Student, Course, and StudentManager.
Students can be enrolled in courses, and you can add, remove, and sort students by
name within courses. The StudentManager class provides a method to sort students by
name. It also demonstrates the use of try-catch blocks to handle exceptions when
attempting to remove a student who is not in the course.

Here's another Java exercise that combines classes, inheritance, error interception
with try-catch, arrays, and array sorting. In this exercise, we'll create a simple
banking system with three classes: Bank, Account, and BankManager. Accounts can be
opened at the bank, and we'll provide functionality to add, remove, and sort
accounts by balance.

java
Copy code
import java.util.Arrays;
import java.util.Comparator;

class Account {
private int accountNumber;
private String accountHolder;
private double balance;

public Account(int accountNumber, String accountHolder, double balance) {


this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = balance;
}

public int getAccountNumber() {


return accountNumber;
}

public String getAccountHolder() {


return accountHolder;
}
public void setAccountHolder(String accountHolder) {
this.accountHolder = accountHolder;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

@Override
public String toString() {
return "Account [Account Number: " + accountNumber + ", Account Holder: " +
accountHolder + ", Balance: " + balance + "]";
}
}

class Bank {
private Account[] accounts;
private int accountCount;

public Bank(int maxAccounts) {


this.accounts = new Account[maxAccounts];
this.accountCount = 0;
}

public void openAccount(int accountNumber, String accountHolder, double


initialBalance) {
if (accountCount < accounts.length) {
accounts[accountCount] = new Account(accountNumber, accountHolder,
initialBalance);
accountCount++;
} else {
System.out.println("Error: The bank is at full capacity. Cannot open
more accounts.");
}
}

public void closeAccount(int accountNumber) {


for (int i = 0; i < accountCount; i++) {
if (accounts[i].getAccountNumber() == accountNumber) {
for (int j = i; j < accountCount - 1; j++) {
accounts[j] = accounts[j + 1];
}
accounts[accountCount - 1] = null;
accountCount--;
return;
}
}
System.out.println("Error: Account not found in the bank.");
}

public Account[] getAccounts() {


return Arrays.copyOf(accounts, accountCount);
}
}
class BankManager {
public static void sortAccountsByBalance(Account[] accounts) {
Arrays.sort(accounts, Comparator.comparingDouble(Account::getBalance));
}

public static void main(String[] args) {


// Create a bank
Bank bank = new Bank(5);

// Open accounts
bank.openAccount(1, "Alice", 1000.0);
bank.openAccount(2, "Bob", 2000.0);
bank.openAccount(3, "Charlie", 1500.0);

// Close an account
bank.closeAccount(2);

// Sort accounts by balance


Account[] sortedAccounts = bank.getAccounts();
sortAccountsByBalance(sortedAccounts);

System.out.println("Bank Accounts:");
for (Account account : bank.getAccounts()) {
System.out.println(account);
}

System.out.println("\nBank Accounts (Sorted by Balance):");


for (Account account : sortedAccounts) {
System.out.println(account);
}
}
}
In this exercise, we have three classes: Account, Bank, and BankManager. Accounts
can be opened at the bank, and you can open, close, and sort accounts by balance.
The BankManager class provides a method to sort accounts by balance and
demonstrates the use of try-catch blocks to handle exceptions when attempting to
close an account that doesn't exist in the bank.

You might also like