Pomoc w rozwiązaniu/obliczeniu łańcucha wejściowego

0

Witam wszystkich chce rozwiązać tego typu zadanie.
Chce to zadanie tak zmienić by obsługiwało również liczby zmiennoprzecinkowe.
Z góry dzięki za poświęcony czas.

  • liczenie od lewej do prawej - tak wiec kolejnosc wykonywania działań nie musi byc spójna matematycznie (np. mnożenie przed dodawaniem itp.)
  • program musi umieć obsługiwać liczby wielocyfrowe (ale tylko całkowite, bez zmiennoprzecinkowych)
  • program nie musi obsługiwać liczb ujemnych
  • program musi ominąc spacje - nie powinny one być brane pod uwagę przy obliczaniu wyniku
  • obsługiwane działania to + - * /
  • w przypadku gdy zostanie podany jakikolwiek znak niedozwolony - program ma wyrzucić wyjatek (np RuntimeException)

przykładowy łańcuch wejściowy "33 * 1 + 1/ 2 -3"

package Ad1;

public class MATHS {

public static void main(String[] args) {
    double result = CalculateMath.calculate("1*33+1/2-3");
    System.out.printf("Result should be 14 == %f", result);

}

}

package Ad1;

public class CalculateMath {

public static double calculate(String mathToCalculate) {
    Integer digit1 = null;
    Integer digit2 = null;
    Double result = null;
    Character typeOfCalculation = null;
    for (int i = 0; i < mathToCalculate.length(); i++) {
        char c = mathToCalculate.charAt(i);
        if (isDigit(c)) {

            if (digit1 == null) {
                digit1 = Integer.parseInt(String.valueOf(c));
            } else if (typeOfCalculation == null && isDigit(mathToCalculate.charAt(i))) {
                digit1 = joinDigits(digit1, Integer.parseInt(String.valueOf(c)));
            } else {
                if (typeOfCalculation != null) { //&& isDigit(mathToCalculate.charAt(i)){
                    if (digit2 == null) {
                        digit2 = Integer.parseInt(String.valueOf(c));
                    } else if (isDigit(mathToCalculate.charAt(i))) {
                        digit2 = joinDigits(digit2, Integer.parseInt(String.valueOf(c)));
                    }

                } else {
                    throw new RuntimeException("Missing type of calculation !!!!");
                }
            }
        } else if (c == '*' || c == '-' || c == '+' || c == '/' || c== '.') {
            if (typeOfCalculation != null) {
                if (result == null) {
                    result = digit1.doubleValue();
                }
                if (digit2 == null) {
                    digit2 = digit1;
                }
                result = calculate(result, digit2.doubleValue(), typeOfCalculation);
                digit2 = null;
                digit1 = null;
            }

            typeOfCalculation = c;
        } else if (c == ' ') {

        } else {
            throw new RuntimeException("Not supported char was passed to the program: " + c + "!!!");
        }
    }

    if (typeOfCalculation != null) {
        if (digit1 != null && digit2 != null) {
            digit2 = joinDigits(digit1, digit2);
        }
        result = calculate(result, digit2.doubleValue(), typeOfCalculation);
    }

    return result;

}

private static int joinDigits(int numberFirst, int digit) {

    String joinedNumbers = String.valueOf(numberFirst) + String.valueOf(digit);
    return Integer.parseInt(joinedNumbers);
}

// TODO FIXME private static String joinDoubles(String numberFirst, String part) {
// //String joinedNumbers = String.valueOf(numberFirst) + String.valueOf(digit);
// }

private static boolean isDigit(char stringElement) {
    if (stringElement <= '9' && stringElement >= '0' )  {
        return true;



    }
    return false;
}


private static double calculate(Double first, Double second, char typeMath) {

    switch (typeMath) {
        case '*':
            return first * second;
        case '/':
            return first / second;
        case '+':
            return first + second;
        case '-':
            return first - second;
        default:
            throw new RuntimeException("Wrong type of math calculation passed as a parameter: " + typeMath + " !");
    }


}

}

0

Podziel całość na 2 części.

  1. Sprawdzenie wyrażenia i rozbicie na pojedyncze elementy
  2. Wykonanie obliczeń

1 - część możesz zrobić łatwo na wyrażeniach regularnych. Przykładowo w podanym ciągu usuwasz białe znaki, przepuszczasz przez regex (\d+\.\d+|\d+|\*|\+|\-|\/)+ i rozbijasz na poszczególne grupy. Jeżeli regex nie przejdzie, to podany ciąg do obliczeń jest nieprawidłowy. Jeżeli jednak przejdzie, to musiałbyś sprawdzić czy liczby występują naprzemiennie z działaniami, ale to możesz zrobić poprawiając samo wyrażenie.
2 - Mając listę już chyba sobie poradzisz.

1 użytkowników online, w tym zalogowanych: 0, gości: 1