JAVA实验四:用HashMap模拟一个网上购物车

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fighting123678/article/details/83903203

题目

用HashMap模拟一个网上购物车。要求:从键盘输入n本书的名称、单价、购买数量,将这些信息存入一个HashMap,然后将该HashMap作为参数调用方法getSum(HashMap books),该方法用于计算书的总价并返回。【说明:键盘输入可使用Scanner类】

答案

import java.util.*;

public class Main 
{
	public static Scanner scan=new Scanner(System.in);
	public static int n=scan.nextInt();
	public static double getSum(HashMap books)
	{
		double sum=0;
		for(int i=0;i<n;i++)
		{
			Book b=(Book)books.get(i);//这个容器没有用泛型,所以别忘记强制类型转换;
			sum+=b.price*b.number;
		}
		return sum;
	}
	public static HashMap purChase()
	{
		HashMap<Integer,Book> hm=new HashMap<Integer,Book>();//注意键值是什么类型的;
		for(int i=0;i<n;i++)
		{
			System.out.print("Please input the book`s name:");
			String name=scan.next();
			System.out.print("Please input the book`s price:");
			double price=scan.nextDouble();
			System.out.print("Please input the book`s number:");
			int number=scan.nextInt();
			Book b=new Book(name,price,number);//别忘记了初始化;
			hm.put(i, b);
		}
		return hm;
	}
	public static void main(String[] args) 
	{
		double s=getSum(purChase());
		System.out.println("The total prices of books is:"+s+".");
	}

}

class Book
{
	String name;
	protected double price;
	protected int number;
	public Book(String name,double price,int number)
	{
		this.name=name;
		this.price=price;
		this.number=number;
	}
}

解析

1、注意键值是什么类型的

2、在要求调用的另外一种方法的时候,没有使用泛型,所以别忘记强制类型转换

猜你喜欢

转载自blog.csdn.net/fighting123678/article/details/83903203