Steve
Steve

Reputation: 91

Calculator issue

I'm doing a calculator app and I have one problem. I can not distinguish negative numbers and subtraction. I use this code to set all numbers apart.

ArrayList<Double> doubles;
String[] strings1 = string.split("\\*");
for (String string2 : strings1) {
    String[] string3 = string2.split("÷");
    for (String string4 : string3) {
        String[] string5 = string4.split("\\+");
        for (String string6 : string5) {
            Log.e("Point_1", "String5 " + string5.toString());
            Log.e("Point_1", "String6 " + string6);
            String[] string7 = string6.split("\\-");
            for (String string8 : string7) {
                doubles.add(Double.parseDouble(string8));
            }
        }
    }
}

What I get is [number1,number2,number3 ...](they all are positive) and in another ArrayList operators like [+,-,+,*,- ...]. What I need is to put in first ArrayList(doubles) all numbers but make them negative if they are. Let me give you an example. If we have a string like "-3+6" then in doubles should be numbers: -3;6 and in the second ArrayList only "+". And vise versa if we have "6-3" then in doubles we should have: 6;3 and in second ArrayList only "-". How can I do this?

Thank you.

Upvotes: 0

Views: 88

Answers (1)

Anonymous
Anonymous

Reputation: 86276

If string8 is an empty string, you may assume it comes from before a leading minus. Replace your innermost for loop with:

                int index = 0;
                while (index < string7.length) {
                    String string8 = string7[index];
                    if (string8.isEmpty()) { // assume there was a leading minus here
                        // reverse sign of next double
                        index++;
                        doubles.add(-Double.parseDouble(string7[index]));
                    } else {
                        doubles.add(Double.parseDouble(string8));
                    }
                    index++;
                }

With this change, given the string -3+6 the code gives [-3.0, 6.0]. With 6-3, [6.0, 3.0] (which is correct because the minus denotes subtraction, not a negative number).

This doesn’t take multiple leading minuses into account, say --3+6. If you wanted to, all you would have to do was to detect multiple empty strings in a row and see if there was an even or an odd number of them.

Upvotes: 1

Related Questions