Question
JAVA Define a method that loops through all books in the array list and prints out the total price of all of the books as
JAVA
Define a method that loops through all books in the array list and prints out the total price of all of the books as well as the average price. Below are the classes.
Book.java
public class Book {
private String title;
private String author;
private double price;
public Book(String title, String author, double price){
this.title = title;
this.author = author;
this.price = price;
}
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [title=" + title + ", author=" + author + ", price=" + price + "]";
}
}
Main.java
import java.util.ArrayList;
import java.util.Scanner;
public class MyProgram{
public static void main (String[] args){
ArrayList
Scanner sc = new Scanner (System.in);
for (int i = 0; i < 4; i++ ){
System.out.println("Enter the title of the book: ");
String title = sc.next();
System.out.println("Enter the author of the book: ");
String author = sc.next();
System.out.println("Enter the price of the book: ");
double price = sc.nextDouble();
Book b = new Book(title, author, price);
myList.add(b);
}
sc.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started