現在我的程序outputing數據我想它想(我與一些System.out.println語句檢查的話),但我想轉換將這兩個數組轉換爲包含兩者的散列表。我不知道如何去做。請幫忙!我想創建一個HashMap了兩個數組,我已經(JAVA)
這裏是我的代碼:
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);
}
}
這裏是它是迄今爲止outputing(這就是我要投入到一個HashMap什麼):
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]
所以,你要食物名稱映射到相應的價格? –
您目前的問題歷史給出了(* strong *)的印象,即您正在使用stackoverflow作爲「作業製作機器」。但是,像這樣的問題*可能是合法的,如果您試圖以更適合Q/A網站的形式對其進行說明,那麼他們可能會變得更好。這指的是措辭的細節(「我想」與「如何」),而且要側重於問題的核心* *:沒有'Scanners',沒有文件,只是一個'有兩個main'方法硬編碼數組。此外,你應該是*精確*哪些數組包含*鍵*和一個包含*值* – Marco13
,如果你映射他們直出文件,這將是最好的。你能從文件中添加一個樣本到你的問題嗎? – RealSkeptic