山科java實驗4-2 用HashMap模擬一個網上購物車。
阿新 • • 發佈:2018-11-19
用HashMap模擬一個網上購物車。要求:從鍵盤輸入n本書的名稱、單價、購買數量,將這些資訊存入一個HashMap,然後將該HashMap作為引數呼叫方法getSum(HashMap books),該方法用於計算書的總價並返回。【說明:鍵盤輸入可使用Scanner類】
package 作業2; public class Books { String name; double price; int numbers; public Books(String name, double price, int numbers) { this.name = name; this.price = price; this.numbers = numbers; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + numbers; long temp; temp = Double.doubleToLongBits(price); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Books other = (Books) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (numbers != other.numbers) return false; if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) return false; return true; } 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 getNumbers() { return numbers; } public void setNumbers(int numbers) { this.numbers = numbers; } }
package 作業2; import java.util.*; public class Booknet { static double getSum(HashMap<Integer, Books> map) { double sum = 0; for(int i = 0;i < map.size();i++) { Books t = map.get(i); sum += (t.getPrice() * t.getNumbers()); } return sum; } public static void main(String[] args) { // TODO Auto-generated method stub HashMap<Integer, Books> m=new HashMap<Integer, Books>(); Scanner sc=new Scanner(System.in); System.out.print("請輸入書的數量:"); int n=sc.nextInt(); for(int i=0;i<n;i++) { System.out.println("請輸入第"+(i+1)+"本書的姓名,價格,數量:"); String nm=sc.next(); double p=sc.nextDouble(); int nb=sc.nextInt(); m.put(i, new Books(nm,p,nb)); } double s= getSum(m); System.out.print("書的總價為:"+s); sc.close(); } }