-4

In a project I am working with a custom configuration file to allow for custom cards to be loaded into a game. (similar to a .properties file except it holds information for more than one item, as well as different types of items).

File is set up like this:

# Pound Signs denote comments
# Empty lines are also ignored by the parser.

# Here are three example items

CARD_TYPE_ONE
{
    name = item one name
    species = robot
    isMoveable = false
}

CARD_TYPE_TWO
{
    name = foo
    attackType = bar
}

CARD_TYPE_TWO
{
    name = foo2
    special = true
    attackType = bar2
}

All cards will have default values for any unassigned attributes (i.e. "special" defaults to "false" under CARD_TYPE_TWO), but as you can see, differnt cards of the same type can have different lengths

The code I have for reading the attributes looks like this:

 private int createCardType2(String cardFile, int expectedLineNumber) {
    // Builds Card type 2.
    //cardFile is the location (with extension) of the .cards file
    //expectedLineNumber is where the main program currently sits in reading the program

    int i = 0;
    Scanner in = null;
    try {
        in = new Scanner(new File(cardFile));
    } catch (java.io.IOException e) { System.out.println(e); }

    int x = 1;
    while (in.hasNext()){

        //loops through the previous lines in the file
        while( i < expectedLineNumber) {
            in.nextLine();
            i++;
        }


        if (i != expectedLineNumber) {
            //Something went wrong, and that can't be right
            System.out.println("We have encountered an error, aborting now.");
            break;
        }

        String <some dynamic name> = in.nextLine();

        if (dynamicallyNamedString.equals("}") {
         //find key pairs and set attributes. 
        }

       if (!dynamicallyNamedString..trim().equals("}") && !in.hasNext()) {
         //malformed file, throw an error
         break;
       }
    }
    in.close();
    return i; //so that the main program knows where to go to to continue.
}

I will use String.split() with " = " as my delimiter to get my key pairs.

I am also aware that Java does not have dynamic variable naming, but I don't think hash-tables are right, and I can't use Arrays because I don't know the initial size.

I feel like I'm missing something quite simple.

Bpendragon
  • 44
  • 1
  • 4

1 Answers1

0

I think a HashMap is exactly right, since you have a collection of dynamic key/value pairs you wish to store in your Cards instnaces. However, you would have to either give up the strong typing (by storing all the values as Strings in a Map) or the type safety (but using a non generic Map and storing values of different types).

However, if you know the set of all possible variables for the various types of cards, you should use inheritance, and define for each CARD_TYPE the class variables statically. Some of them may be optional.

Eran
  • 387,369
  • 54
  • 702
  • 768