This is a continuation of my previous post.
I've changed my mind and I have decided that having spaces in the mana cost is completely ugly. I want "1GG" not "1 G G". (MTG Forge currently requires mana costs to have spaces because it is easier to decode.) I want to keep all of my beautifully written mana code, so last night I wrote the addSpaces() method, which converts "1GG" into "1 G G" so the existing code will still work. The user won't know that internally MTG Forge uses spaces in the mana cost because I will remove the spaces when I show the mana cost to the user.
The addSpaces() method is not complicated and consists of only eight lines but it still very useful. I wasn't sure of the exact logic, so I wrote a method and kept tweaking it until it worked. (This "discovery" process is good for short methods but I wouldn't use it for anything bigger than a class or two. Even I have to pseudocode the hard stuff in order to make sure it works.)
The addSpaces() method is one of the million bits of code in MTG Forge. Another code tidbit checks to see if a creature has enough damage and should be put into the graveyard. While it is only six lines, it is still very important, the same goes for the code that untaps everything. The goal is to write it and then forget about it because the code works so well. When I'm working on another part of MTG Forge I don't want to think about addSpaces() or the untap code, I just want it to work.
As a bonus you can see the Java code that converts a card name into a URL so you can download the picture from wizards.com. (I stole this code from another Magic project, Nate's Deckbuilder.)
//converts "1GG" to "1 G G"
String addSpaces(String manaCost)
String out = "";
int i = 0;
out = manaCost.substring(0, i) +" ";
for( ; i < manaCost.length(); i++)
out += manaCost.charAt(i) +" ";
//URL to download card pictures from Wizards
String name = "Elvish Piper".replace(", ", "_").replaceAll("[ -]", "_").replaceAll("[':\"!]", "").toLowerCase();
String url = "http://mi.wizards.com/global/images/magic/general/" + name + ".jpg";
addSpaces() still isn't quite right, can you spot the error? Which one of these test cases breaks addSpaces, "G", "GG", "10", "10GGG"? For a hint see Stratadon. Even short code is hard to get 100% correct. (Wizards has updated Gatherer for better or worse.)