1
public static void save() 
{
    BufferedWriter out = null;
    try 
    {
        out = new BufferedWriter(new OutputStreamWriter(Gdx.files.external(file).write(false)));
        out.write(Double.toString(FinanceSystem.currentPlayerCash));
        out.write("\n");
        out.write(Integer.toString(DateSystem.day));
        out.write("\n");
        out.write(Integer.toString(DateSystem.month));
        out.write("\n");
        out.write(Integer.toString(DateSystem.year));
        out.write("\n");
        for(int i = 0; i <= InventorySystem.drugsOwned.size(); i++)
            out.write(Integer.toString(InventorySystem.drugsOwned.get(i))+"\n");
        for(int i = 0; i <= AttributeSystem.attributeNames.length; i++)
            out.write(Integer.toString(AttributeSystem.attributeValues.get(i)) + "\n");



    } 
    catch (Throwable e) {} 
    finally 
    {
       try
       {
          if (out != null)
               out.close();
       } 
       catch (IOException e) {}
    }

My problem is that after the for loop for the inventory system.drugsowned nothing else gets wrote to file. So in this example AttributeSystem.attributeValues doesnt get wrote. I have also tried putting other things to be wrote after this loop including non loop things and they also haven't wrote. Whagwaan?

4

1 回答 1

7

这就是问题:

for(int i = 0; i <= InventorySystem.drugsOwned.size(); i++)
    out.write(Integer.toString(InventorySystem.drugsOwned.get(i))+"\n");

<=应该是<一个. 因此,如果集合中有 5 个项目,则您要求元素 5,这是第6 个元素,因为索引是从 0 开始的。那会抛出异常。

然后被这个掩盖了:

catch (Throwable e)
{
}

就诊断而言,您在这里完全是自责:

  • 除非您真的可以处理异常,否则不要捕获它 - 或捕获它然后在记录后重新抛出它(或其他)
  • 尽可能捕捉特定异常。(捕捉Exception不好;捕捉Throwable更糟。)
  • 在没有记录的情况下默默地捕捉是一个糟糕的主意。这意味着您不知道您遇到问题的频率,或者问题是什么。

(此外,代码表明您要么过度使用静态变量,要么需要整理命名约定。不过那是另一回事。)

于 2012-01-06T19:52:38.600 回答