【发布时间】:2015-10-19 19:00:29
【问题描述】:
现在我的程序正在输出我想要的数据(我用一些 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]
【问题讨论】:
-
那么您想将食物名称映射到相应的价格中吗?
-
您当前的问题历史给人的印象是(strong)您将 stackoverflow 用作“家庭作业制作机”。但是,像这样的问题可能是合法的,如果您尝试以更适合 Q/A 网站的形式来表达它,那么它们可能会被更好地理解。这指的是措辞的细节(“我想”与“如何”),但也关注问题的核心:没有
Scanners,没有文件,只是一个@ 987654325@ 具有两个硬编码数组的方法。此外,您应该精确了解哪个数组包含 keys 以及哪个数组包含 values -
最好直接从文件中映射出来。您可以将文件中的示例添加到您的问题中吗?
-
@RealSkeptic 见stackoverflow.com/questions/33219776/… ... ... ...
-
@Marco13 有趣。然后我想知道
split(":")将如何工作......我想你之前的评论是有道理的。