Вылетает постоянно с ошибкой Invalid index 1, size is 1 (для ArrayList). Но дело в том, что while уже передано значение false и он по всем законам логики не должен запуститься еще раз. Даже попытка поставить дополнительную проверку if (mathMap.size() != 1) не приводит ни к чему, она просто игнорируется.
Может кто глянуть код и сказать. Заранее благодарен!
З.Ы.
Прикрепил файл проекта.
Код: Выделить всё
int openB = 0;
int closeB = 0;
String math = "1+(2*3/4+5)+6+(7+8)";
String result = "";
ArrayList<String> mathMap = new ArrayList<String>();
parse(math);
while (findBeakets()) {
while (findDivMul())
;
while (findAddSub())
;
}
readList();
public void parse(String s) {
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
mathMap.add(String.valueOf(s.charAt(i)));
} else {
mathMap.add(String.valueOf(s.charAt(i)));
}
}
}
public void readList() {
for (int i = 0; i < mathMap.size(); i++) {
result += mathMap.get(i);
}
Log.d("TAG", result);
result = "";
}
public boolean findBeakets() {
for (int i = 0; i < mathMap.size(); i++) {
if (mathMap.get(i).equals("(")) {
openB = i;
}
if (mathMap.get(i).equals(")")) {
closeB = i;
if ((closeB - openB) == 2) {
mathMap.remove(openB);
mathMap.remove(closeB - 1);
findBeakets();
}
return true;
}
}
openB = 0;
closeB = mathMap.size();
return false;
}
public void delElement(int i) {
mathMap.remove(i - 1);
mathMap.remove(i);
closeB = closeB - 2;
}
public boolean findDivMul() {
if (mathMap.size() != 1) {
for (int i = openB; i < closeB; i++) {
if (mathMap.get(i).equals("/")) {
mathMap.set(i, ((Integer.parseInt(mathMap.get(i - 1))) / (Integer.parseInt(mathMap.get(i + 1)))) + "");
delElement(i);
findDivMul();
}
if (mathMap.get(i).equals("*")) {
mathMap.set(i, ((Integer.parseInt(mathMap.get(i - 1))) * (Integer.parseInt(mathMap.get(i + 1)))) + "");
delElement(i);
findDivMul();
}
}
}
return false;
}
public boolean findAddSub() {
if (mathMap.size() != 1) {
for (int i = openB; i < closeB; i++) {
if (mathMap.get(i).equals("+")) {
mathMap.set(i, ((Integer.parseInt(mathMap.get(i - 1))) + (Integer.parseInt(mathMap.get(i + 1)))) + "");
delElement(i);
findAddSub();
}
if (mathMap.get(i).equals("-")) {
mathMap.set(i, ((Integer.parseInt(mathMap.get(i - 1))) - (Integer.parseInt(mathMap.get(i + 1)))) + "");
delElement(i);
findAddSub();
}
}
}
return false;
}