[英]Java - How to Loop and Print Values From 2 HashMaps on the Same Line?
我找到了相关的问题,但是我不确定如何使用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));
}
}
}
如果您不希望换行,请使用print
而不是println
(因为您希望将文本保持在同一行,因此不希望使用换行。只记得以println()或\\n
结尾以获取下一个记录)线)。
为了您自己的理智,您可能想引入一个具有优先级,名称和价格的Product
类。 但是要回答以下问题:
pMap.forEach((p, n) -> System.out.format("%d %s $%2f\n", p, n, priceMap.get(p)));
如果创建了Product
类(推荐),其自然顺序 ( implements Comparable<Product>
)是由priority
定义的,则可以将它们存储在TreeSet<Product>
。 然后,将按优先级对集合进行迭代。
您可以同时遍历两个地图,并根据其优先级索引访问元素。
for (int priority : pMap.keySet()) {
System.out.print(priority); //prints the priority
System.out.print(pMap.get(priority)); // prints the product for the priority
System.out.print(priceMap.get(priority)); //prints the price
System.out.println(); // changes the line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.