I have a simple issue but it’s been driving me nuts lately.
I’m making a Chemistry program (Android app, to be more specific) and I have a method that separates elements that the user inputs. For example, if someone where to enter “FeZnKPb”, it would be separated into “Fe”, “Zn”, “K”, and “Pb”.
To do so, I’m using a few nested loops and variables to control it. I have all the elements defined in the Chem[] array. The separated elements are then stored in an array called savedChem[]. It basically just loops through all the element constants (Chem[]) and copies the name and formula of those elements into savedChem[] if it matches the input.
Here is my code for this:
public void separateElements(String Input)
{
boolean found = false;
int start = 0;
int end = 2;
int length = Input.length();
while(length >= end)
{
for(int x = 0; x < numChemicals; x++)
{
if((end + 0) > length)
{
end += 5;
break;
}
if(Input.substring(start, end).equals(Chem[x].getFormula()))
{
savedChem[numSaved].setName(Chem[x].getName());
savedChem[numSaved].setFormula(Chem[x].getFormula());
numSaved++;
start += 2;
end += 2;
found = true;
}
else
{
found = false;
}
}
if(!found)
{
start += 2;
end += 2;
}
}
}
My problem is that it only works with 2-character elements such as “Fe” or “Zn”. I want it to also recognize others like “K”.
Another issue is that it sometimes skips some other elements. For example, if I were to input “FeZnHg” it would separate them into “Fe”, “Zn”, and “Hg”. However, if I enter them in a different order like “ZnFeHg”, it only detects “Zn” and “Hg” but not “Fe” for some reason.
What other ways am I able to solve this to get it to work correctly?
Given that elements are always either an upper case character and one or two lower case characters (and two only in the case of some very short lived elements), you can just use a regex with some lookahead to split your input into short strings.
You can split your string up into element strings with the split method and some lookahead. Taking Nathaniel Ford’s comments into account:
So a test input like this:
will give you the following list:
[Fe, Zn, K, Pb, Umm, K]