我必须编写一个程序,将用户的化学方程式作为输入,例如 12 CO2 + 6 H2O -> 2 C6H12O6 + 12 O2,并观察两个站点上的原子量是否相同。有什么方法可以轻松计算和解析吗?
例如:
12 CO2 + 6 H2O -> 2 C6H12O6 + 12 O2
12*2+6*2 -> 2*6+2*12+2*6+12*2
在这种情况下,应该有输出“假”。
这是我的代码,但实际上只是为了尝试一些东西:
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);
}
list.remove(list.size() - 1);
for (int i = 0; i < list.size(); i++) {
int before = 0;
int after = 0;
String string = list.get(i);
string = besserUmwandeln(string);
System.out.println(string);
}
}
public static String besserUmwandeln(String string) {
string = string.replace("-", "");
string = string.trim().replaceAll(("\\s+"), " ");
string = string.replace(' ', '*');
StringBuilder builder = new StringBuilder(string);
System.out.println(string);
for (int k = 0; k < builder.length(); k++) {
if (Character.isUpperCase(builder.charAt(k))) {
builder.setCharAt(k, ':');
}
if (Character.isLowerCase(builder.charAt(k))) {
builder.setCharAt(k, '.');
}
if (Character.isDigit(builder.charAt(k))) {
} else {
}
}
for (int j = 0; j < builder.length(); j++) {
if (j < builder.length() && builder.charAt(j) == ':' && builder.charAt(j + 1) == '.') {
builder.deleteCharAt(j + 1);
}
}
for (int i = 0; i < builder.length(); i++) {
if (i < builder.length() - 1 && builder.charAt(i) == ':' && builder.charAt(i + 1) == ':') {
builder.deleteCharAt(i);
}
}
for (int i = 0; i < builder.length(); i++) {
if (i < builder.length() - 1 && builder.charAt(i) == '+' && builder.charAt(i + 1) == '*') {
builder.deleteCharAt(i + 1);
}
}
for (int i = 0; i < builder.length(); i++) {
if (i < builder.length() - 1 && builder.charAt(i) == '*' && builder.charAt(i + 1) == '+') {
builder.deleteCharAt(i);
}
}
for (int i = 0; i < builder.length(); i++) {
if (i < builder.length() - 1 && builder.charAt(i) == '*' && builder.charAt(i + 1) == '>') {
builder.deleteCharAt(i);
}
}
for (int i = 0; i < builder.length(); i++) {
if (i < builder.length() - 1 && builder.charAt(i) == '>' && builder.charAt(i + 1) == '*') {
builder.deleteCharAt(i + 1);
}
}
for (int i = 0; i < builder.length(); i++) {
if (i < builder.length() - 1 && builder.charAt(i) == '*' && builder.charAt(i + 1) == ':') {
builder.deleteCharAt(i + 1);
}
}
return builder.toString();
}