import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
public class mainClass
{
static Scanner keyboard = new Scanner(System.in);
static HashMap <ArrayList <Integer>, String> hMap;
public static void createAHashMap()
{
System.out.print("Express the initial capacity: ");
int initialCapacity = keyboard.nextInt();
System.out.print("Express the load factor: ");
float loadFactor = keyboard.nextFloat();
hMap = new HashMap <ArrayList <Integer>, String> (initialCapacity, loadFactor);
}
public static void insertProduct()
{
ArrayList <Integer> informations = new ArrayList <Integer>();
System.out.print("\nEnter product's barcode number: ");
int barcodeNumber = keyboard.nextInt();
while (barcodeNumber < 0)
{
System.out.println("Wrong barcode number entry. Please try again: ");
}
informations.add(barcodeNumber);
System.out.print("Enter product's amount: ");
int productAmount = keyboard.nextInt();
informations.add(productAmount);
System.out.print("Enter product's price: ");
int productPrice = keyboard.nextInt();
informations.add(productPrice);
System.out.print("Enter product's name: ");
String productName = keyboard.next();
hMap.put(informations, productName);
}
public static void displayProducts()
{
System.out.println("\nBarcode Number\tProduct Amount\tProduct Price\tProduct Name");
for (Entry <ArrayList <Integer>, String> entry: hMap.entrySet())
{
for(int itemNo: entry.getKey())
{
System.out.print(itemNo + "\t\t");
}
System.out.print(entry.getValue() + "\t\t");
System.out.println();
}
}
public static void removeAProduct()
{
System.out.print("Express product name that you want to remove: ");
String productName = keyboard.next();
hMap.remove(productName);
}
/* public static void updateAProduct()
{
System.out.print("Express product name that you want to update: ");
String productName = keyboard.next();
hMap.remove(productName);
System.out.println("Enter again the product informations");
insertProduct();
}*/
public static void main(String args[])
{
createAHashMap();
System.out.print("\nEnter '1' to add a product\n");
System.out.print("Enter '2' to display products\n");
System.out.print("Enter '3' to delete a product\n");
System.out.print("Enter '4' to update a product\n");
System.out.print("Enter your choice: ");
int entry = keyboard.nextInt();
while (entry != -99)
{
if (entry == 1)
{
insertProduct();
}
if (entry == 2)
{
displayProducts();
}
if (entry == 3 && hMap.size() != 0)
{
removeAProduct();
}
if (entry == 4 && hMap.size() != 0)
{
//updateAProduct();
}
System.out.print("\nExpress your new choice (Exit: -99): ");
entry = keyboard.nextInt();
}
}
}
我創建了一個哈希映射,其中包含超市中的產品信息。但是,我無法刪除我輸入的產品名稱。顯然,我不能使用刪除方法。有什麼問題,我該如何糾正?從哈希映射中刪除項目時遇到問題
非常感謝你@Sparta。我想問另一個問題。如果我想用條形碼號碼刪除會發生什麼? – lzxcl
好,臨時解決方案是使用'informations' arraylist的第一項,但我認爲你需要第二個'Map',像'靜態HashMap,String> hMap;'。你應該考慮使用產品名稱來索引你的Map,而不是它的信息。 –