[英]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.