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.