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 myList = new 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!