4

I am programming a game and almost have the save-file system complete. I have two Vectors (one holds the name of the savegame, one holds the sessionID).

At launch, the program will read in data from a file and add that information to the Vectors. Then another method is called to check if the files shown in the Vector acctualy exist. If not, they will be removed from the Vectors. At the end, the Vectors are printed to and rewrite the file.

The problem I'm having is the for loop isn't checking every item in the Vector, because Vector.size() is decreasing when items are removed.Is there a better way to form the for loop, or is there a workaround I can use?

private static void slistCleanup() throws IOException {

          private static Vector<String> saveNames = new Vector<String>();
          private static Vector<Integer> sessionIDs = new Vector<Integer>();

    Scanner slistReader = new Scanner(new FileReader(sessionList));
    File tempSave;
    String path;
    int run = 1;
    String tempName = " ";
    int tempID = 0;

    for (int x = 0; x < saveNames.size(); x++) {

        path = currentDir + "\\saves\\" + sessionIDs.elementAt(x) + ".sav";
        tempSave = new File(path);

        System.out.println("-----------------------"); //debug
        System.out.println("current pass: " + run);
        System.out.println("tempSave Path: " + tempSave.getAbsolutePath()); //debug
        System.out.println("tempSave exists: " + tempSave.exists()); //debug
        System.out.println("-----------------------"); //debug
        run++; //debug

        if (!tempSave.exists()) {

            saveNames.remove(x);
            sessionIDs.remove(x);
        }
    }

    for (int x = 0; x < saveNames.size(); x++) {

        System.out.println(saveNames.elementAt(x));
        System.out.println(sessionIDs.elementAt(x));
    }

    slistReader.close();
}

If you need more code, let me know.

4

8 に答える 8

2

Fildor がコメントで指摘したように、イテレータを使用してこれを行うことができます

Iterator namesItr = saveNames.iterator();
Iterator sessionItr = sessionIDs.iterator();
while(namesItr.hasNext() && sessionItr.hasNext()) {
    Object currentName = namesItr.next();
    Object currentSession = sessionItr.next();
    if (!tempSave.exists()) {
        namesItr.remove();
        sessionItr.remove();
    }
}
于 2013-04-30T15:24:02.737 に答える
0

私の意見では、ループを介してアイテムを削除する最良かつ簡単な方法は次のとおりです。

  1. forループを使用してアイテムをスキャンし、削除するアイテムのitemsToDeleteリストを追加します。
  2. list.removeAll(itemsToDelete)
于 2015-11-11T13:12:38.317 に答える