我正在从一个非常简单的文件中读取项目以及它们的成本。它看起来像这样:从文件中读取而不使用扫描器
Shoes 10.00
Jersey 20.00
Cookies 15.00
Light Bulbs 2.00
Paper 5.00
我想映射每个项目到多少成本和我目前的代码工作得很好。然而,它看起来有点笨重,并用null初始化变量,我的项目的提交服务器不喜欢并将其视为错误。我正在寻找一种方法将其转换为更优雅的东西,从而学习如何依靠Scanner类来读取文件。也许使用BufferedReader或PrintReader或者我从未真正掌握的其他内容。帮助赞赏。
private TreeMap<String, Double> prices = new TreeMap<String, Double>();
public void readFromFile(String fileName){
File file = new File(fileName);
Scanner sc = null; //Server treats this as a bug.
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc.hasNextLine()) {
Scanner sc2 = new Scanner(sc.nextLine());
while (sc2.hasNext()) {
String s = sc2.next(); //Gets the item name
prices.put(s, Double.parseDouble(sc2.next())); //The next word is the price
}
sc2.close();
}
}
而不是做try/catch,你可以使用'throws'作为例外,它会让你直接把'sc'分配给'new Scanner(file)' – pushkin
是的,可以一直这样做,但是零件事情只是一种偷偷摸摸的方式来发现如何做到这一点。我一直使用扫描仪来寻找不同的东西。感谢您的输入。 –
如果你对'BufferedReader'感兴趣,只需看一下网上的例子 - [很多](http://stackoverflow.com/questions/16265693/how-to-use-buffered-reader-in-java)。 – pushkin