2015-11-29 35 views
1

我正在从一个非常简单的文件中读取项目以及它们的成本。它看起来像这样:从文件中读取而不使用扫描器

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(); 
        } 
} 
+0

而不是做try/catch,你可以使用'throws'作为例外,它会让你直接把'sc'分配给'new Scanner(file)' – pushkin

+0

是的,可以一直这样做,但是零件事情只是一种偷偷摸摸的方式来发现如何做到这一点。我一直使用扫描仪来寻找不同的东西。感谢您的输入。 –

+0

如果你对'BufferedReader'感兴趣,只需看一下网上的例子 - [很多](http://stackoverflow.com/questions/16265693/how-to-use-buffered-reader-in-java)。 – pushkin

回答

1

这里是一个例子。引发异常,而不是在方法内处理它们。 BufferedReaderStringTokenizer用于从文件中获取所需的文本。

private TreeMap<String, Double> prices = new TreeMap<String, Double>(); 

public void readFromFile(String fileName) throws FileNotFoundException, IOException { 
    BufferedReader br = new BufferedReader(new FileReader(fileName)); 
    StringTokenizer st; 
    String line; 
    while ((line = br.readLine()) != null) { 
     st = new StringTokenizer(line.trim(), " "); 
     prices.put(st.nextToken(), Double.parseDouble(st.nextToken())); 
    } 
    br.close(); 
} 

如果fileNamenull一个NullPointerException将自动被抛出。如果你想通过你的方法处理,你可以在你的方法的顶部添加下面的代码:

if (fileName == null) { 
     throw new IllegalArgumentException("Invalid String input for fileName. fileName: " + fileName); 
    } 
+0

没有办法做到这一点,而不抛出异常(因为在别处处理更加痛苦)并且没有任何空分配开始?我只是好奇。 –

+0

您可以使用'try ... catch'在方法内处理异常。但这不是一个好方法。 –

0

而不是使用trycatch语句中,你可以使用throws异常处理。

public void readFromFile(String fileName) throws FileNotFoundException { 
    File file = new File(fileName); 
    Scanner sc = new Scanner(file); 
    ... 
} 

这应该解决您的服务器的问题,治疗null分配作为一个bug。