簡體   English   中英

我想從我擁有的兩個數組中創建一個 HashMap (Java)

[英]I want to create a HashMap out of two arrays that I have (Java)

現在我的程序正在輸出我想要的數據(我用一些 system.out.println 語句檢查了它)但我想將兩個數組轉換成一個包含兩者的哈希圖。 我不知道如何去做。 請幫忙!

這是我的代碼:

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;

public class Vending2 
{
  public static void main(String[] args) throws FileNotFoundException
  {
      System.out.print("Enter your food selection file: ");      // User inputs file
      Scanner input = new Scanner(System.in);                       // Keyboard input from user
      String filename = input.nextLine();
      Scanner fs = new Scanner(new File(filename));         // Scans in the file that was inputed

        String line;
        double price;
        int num = 0;
        while(fs.hasNextLine()){
             line = fs.nextLine();
             price = Double.parseDouble(line.split(":")[0]);
             num++;
        }

        fs.close();
        fs = new Scanner(new File(filename));

        double[] value = new double[num];                        //Array for prices
        int i = 0;
        while(fs.hasNextLine()){
             line = fs.nextLine();
             price = Double.parseDouble(line.split(":")[0]);
             value[i] = price;
             i++;
        }
        System.out.println(Arrays.toString(value));

        fs.close();
        fs = new Scanner(new File(filename));

         ArrayList<String> foods = new ArrayList<String>();  
        while( fs.hasNext()){

            String str = fs.nextLine();
            String words[] = str.split(":");
            if (words.length > 0){

                for(int j=1; j < words.length; j++){
                    foods.add(words[j]);
                }
            }
        }
        System.out.println("foods="+foods);


    }
  }

這是到目前為止輸出的內容(這是我想放入哈希圖中的內容):

1.0, 1.5, 1.5, 2.0, 1.0, 1.0, 1.25, 0.75, 1.0, 1.0, 1.0, 1.5, 1.25, 0.5, 0.5, 0.5, 3.5, 1.75, 0.25, 1.5]
foods=[Honey roasted peanuts, Cheetos, Bugles, Synder’s Pretzels, Snickers, Twix, M n Ms, Life savers, Twizzlers, Nutter Butters, Butter Fingers, King Size Kit Kats, Carrot sticks, Juicy Fruit, Spearmint Gum, Five gum, Pepperoni, Cheez-Its, Slim Jim, Lays Barbeque Chips]

假設foods列表和value數組的長度始終相同,因此您可以將它們循環在一起。

Map<String, Double> map = new HashMap<String, Double>();

int i = 0;
while (i < foods.size() && i < value.length) { //for safety i will check on both sizes
    map.put(foods.get(i), value[i]);
    i++;
}

如果您的兩個數組/列表具有相同的長度,請執行以下操作:

Map<String, Double> map = new HashMap<>();
for (int i = 0; i < value.length; i++) {
    map.put(foods[i], value[i]);
    // or map.put(foods.get(i), value[i]) if foods is a List
}

假設一種食物只有一種價格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM