【发布时间】:2017-02-19 11:58:27
【问题描述】:
我发现了相关问题,但我不确定如何使用 for 循环来做到这一点。我有两个由用户输入填充的 HashMap。两张地图都有匹配的键。我正在尝试提出一个最终报告,该报告将提取每个地图的匹配键和值,所有这些都打印在同一行上。截至目前,我的代码正在打印第一个 HashmMap(Products),然后是第二个 MashMap(Price) 的值。
电流输出
Priority Product Price
1 apple
2 banana
3 orange
$ 43.81
$ 69.64
$ 96.35
我考虑过创建第三个哈希图并将所有值合并为一个,但我不确定这是否真的有效。
期望的输出
Priority Product Price
1 apple $ 43.81
2 banana $ 69.64
3 orange $ 96.35
我的代码
import java.util.*;
public class Testing
{
String products;
int priority;
double price;
Scanner keyboard = new Scanner(System.in); //Scanner
HashMap<Integer, String> pMap = new HashMap<Integer, String>(); // Product HashMap
HashMap<Integer, Double> priceMap = new HashMap<Integer, Double>(); //Price HashMap
Random r = new Random(); //Random number
public void testingItems()
{
for ( int count = 0; count < 3; count++)
{
//Ask for user input to Add product name and product priority
System.out.println("\nEnter a Product");
products = keyboard.nextLine();
System.out.println("\nEnter a Priority");
priority = keyboard.nextInt();
price = (r.nextDouble() * 100);
//System.out.print(price);
keyboard.nextLine();
//*** HASHMAPS ***
//Add product and priority to HashMap
pMap.put(priority, products);
priceMap.put(priority, price);
System.out.println("Product: "+ products + "\t\t" + "Priority: " + priority + "\n\n" + "Price:" + " $ "+ price);
}
System.out.println("\nPriority " + " Product " + " Price");
System.out.println("----------------------------------------");
for (Integer key: pMap.keySet())
{
System.out.println(key + "\t" + pMap.get(key));
}
for (Integer key2: priceMap.keySet()){
System.out.println("$ " + priceMap.get(key2));
}
}
}
【问题讨论】:
-
您能否完善您的问题,我认为您是在尝试迭代 2 [任意] 地图并将它们各自的值打印到同一行?
-
是的,我就是这个意思。我在遍历两个地图时遇到了麻烦,同时确保输出值会打印在同一行。
-
HashMap不保留插入顺序,这意味着不能保证您的两个关键循环将以相同的顺序运行。如果您想坚持使用 2 张地图,请考虑改用LinkedHashMap。