I have a program that should read a few Strings from the console. If the String "end" appears, it should start to calculate and write a String in the console.
The String which I am reading is a chemical equation. The equation is split with these two characters: ->
. I should prove whether the amount of atoms on both sides is the same. I found this post and tried to implement it but I have a problem with the regex.
For example:
My regex can read and calculate a chemical equation if there is a digit before the formula:
2 HCl + 2 Na -> 2 NaCl + H2
but if there is no digit, then it doesn't calculate it correctly:
HCl + Na -> NaCl + H2
My Code:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
List<String> list = new ArrayList<String>();
String input = "";
while (!(input.equals("end"))) {
input = s.nextLine();
list.add(input);
}
int before = 0;
int after = 0;
list.remove(list.size() - 1);
for (int i = 0; i < list.size(); i++) {
String string = list.get(i);
string = string.replace("-", "");
String[] splitted = string.split(">");
Pattern firstPattern = Pattern.compile("(\\d+) (\\w+)");
Matcher firstMatcher = firstPattern.matcher(splitted[0]);
while (firstMatcher.find()) {
int element = Integer.parseInt(firstMatcher.group(1));
String count = firstMatcher.group(2);
final Pattern pattern = Pattern.compile("\\d+"); // the regex
final Matcher matcher = pattern.matcher(count); // your string
final ArrayList<Integer> ints = new ArrayList<Integer>(); // results
while (matcher.find()) { // for each match
ints.add(Integer.parseInt(matcher.group())); // convert to
// int
}
for (int j = 0; j < ints.size(); j++) {
before = before + element * ints.get(j);
}
}
Pattern secondPattern = Pattern.compile("(\\d+) (\\w+)");
Matcher secondMatcher = secondPattern.matcher(splitted[1]);
while (secondMatcher.find()) {
int element = Integer.parseInt(secondMatcher.group(1));
String count = secondMatcher.group(2);
final Pattern pattern = Pattern.compile("\\d+"); // the regex
final Matcher matcher = pattern.matcher(count); // your string
final ArrayList<Integer> ints = new ArrayList<Integer>(); // results
while (matcher.find()) { // for each match
ints.add(Integer.parseInt(matcher.group())); // convert to
// int
}
for (int j = 0; j < ints.size(); j++) {
after = after + element * ints.get(j);
}
}
if (before == after) {
System.out.println("formally correct");
} else {
System.out.println("incorrect");
}
}
}
Here are some example chemical equations for trying out:
Input:
HCl + Na -> NaCl + H2
2 HCl + 2 Na -> 2 NaCl + H2
12 CO2 + 6 H2O -> 2 C6H12O6 + 12 O2
end
Output:
incorrect
formally correct
incorrect