MId Sem Java Anser
MId Sem Java Anser
Write
setter methods to set the values of these variables, but ensure that price is greater than 0. If an
invalid price is set, print an error message. Use getter methods to retrieve and display the
details of the book in the main method.
import java.util.Scanner;
class Book {
// Private instance variables
private String title; private
String author; private double
price; // Setter method for title
public void setTitle(String title) {
this.title = title;
}
// Getter method for title
public String getTitle() {
return title;
}
// Setter method for author public
void setAuthor(String author) {
this.author = author;
}
// Getter method for author
public String getAuthor() {
return author;
}
// Setter method for price with validation
public void setPrice(double price) {
if (price > 0) {
this.price = price;
} else {
System.out.println("Error: Price must be greater than 0.");
}
}
}}