作业3 容器 3、用HashMap模拟一个网上购物车

作业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);

	}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值