private static int operatorCount(String formule) { int resultaat = 0; for (int c =0; c<operators.length; c++) { if (formule.indexOf(operators[c]) >= 0) { resultaat++; } } return resultaat; }
public class FormuleBereken { static char[] operators = {'*', '+','-'}; static Integer bereken(String formule) { formule = cleanUp(formule); int resultaat = 0; for(int i = 0; i< operators.length; i++) { int position = formule.indexOf(operators[i]); if (position > -1) { int start = position-1; while ((start>0)&&(Character.isDigit(formule.charAt(start-1)))) { start --; } String str1 = formule.substring(start, position); String str2 = formule.substring(position + 1); String subFormule = formule.substring(start); System.out.println(str1); //ERROR: Want hij geeft een string mee "2+1" en dat kan niet int value1 = Integer.parseInt(str1); int value2 = Integer.parseInt(str2); switch( operators[i]) { case '*': resultaat = value1 * value2; break; case '+': resultaat = value1 + value2; break; case '-': resultaat = value1 - value2; break; } formule = formule.replace(subFormule, Integer.toString(resultaat)); if (operatorCount(formule)!=0) { resultaat = bereken(formule); } } } return resultaat; } // EM: deze geeft nog niet het goede resultaat , want hij telt elke operator maar een keer. BDV :dubbele for loop? private static int operatorCount(String formule) { int resultaat = 0; for (int c =0; c<operators.length; c++) { if (formule.indexOf(operators[c]) >= 0) { resultaat++; } } return resultaat; } private static String cleanUp(String formule) { String newFormule = formule.replaceAll(" ", ""); return newFormule; } }
B - parts in brackets () O - can't remember D - divisions M - multiplications A - additions S - subtractions
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)