作业3 容器 3、用HashMap模拟一个网上购物车
要求:从键盘输入n本书的名称、单价、购买数量,将这些信息存入一个HashMap,然后将该HashMap作为参数调用方法getSum(HashMap books),该方法用于计算书的总价并返回。【说明:键盘输入可使用Scanner类】
代码
Main.java
//Main.java
import java.util.HashMap;
import java.util.Scanner;
/*
* 用HashMap模拟一个网上购物车。
* 要求:
* 从键盘输入n本书的名称、单价、购买数量,将这些信息存入一个HashMap,
* 然后将该HashMap作为参数调用方法getSum(HashMap books),
* 该方法用于计算书的总价并返回。
* 【说明:键盘输入可使用Scanner类】
*/
class Book {
private String name;
private double price;
private int quantity;
public Book() {
this(null, 0.0, 0);
}
public Book(String name, double price, int quantity) {
super();
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
public class Main {
static double getSum(HashMap<Integer, Book> books) {
double sum = 0;
Book b = new Book();
for (int i = 0; i < books.size(); i++) {
b = (Book) books.get(i);
sum += (b.getPrice() * b.getQuantity());
}
return sum;
}
public static void main(String[] args) {
HashMap<Integer, Book> hm = new HashMap<Integer, Book>();
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the number of books:");
int bnum = scanner.nextInt();
for (int i = 0; i < bnum; i++) {
Book book = new Book();
System.out.print("Please enter the name of the " + (i + 1) + "th book:");
book.setName(scanner.next());
System.out.print("Please enter the price of the " + (i + 1) + "th book:");
book.setPrice(scanner.nextDouble());
System.out.print("Please enter the quantity of the " + (i + 1) + "th book:");
book.setQuantity(scanner.nextInt());
hm.put(i, book);
}
double sum = getSum(hm);
System.out.println("The total price of these books is " + sum);
}
}