首页 > 解决方案 > 从左到右而不是从右到左扫描字符串计算总数

问题描述

我基本上是想找出一种可以从左到右扫描字符串的技术,它会给我它的整数。从右到左开始很容易,如下面的代码所示。我只是在努力寻找一种方法来添加每个整数以使其成为应有的正确值。

输出:你想输入一个表达式吗?y 输入表达式 2567 value = 7652

我试图让输出的顺序正确。

e = String input // string needing to be converted to double
p = 0 // position
// If a substring of e whose rightmost character is at position p
    // represents a number (possibly with a decimal point, possibly negative),
    // return the numerical value of the substring as a double value and
    // re-position p just to the left of the substring.

    private double formNum() {

        double total = 0.0;
        int count = 0;
        int flag = 0;
        double mult = 1;
        char c, d;
        do {
            c = e.charAt(p); // examine the current character in the string (from right to left)
            if (c == '.') {
                flag = 1; // set a flag to remember that the character is a decimal point
            } else {
                // if the current character is a digit, convert to its
                // int value and include it in the value corresponding to the string.
                if ((c >= '0') && (c <= '9')) {
                    
                    total = total + mult * (c - '0');
                    mult = mult * 10.0;
                    if (flag == 0) {
                        count++; // count the number of digits to the right of a possible decimal point
                    }
                } else {
                    if (c == '(' && e.charAt(p + 1) == '-') {
                        total = -total; // an underscore character represents a negative value
                    }
                }
            }
            p++; // Prepare to move to the next character to the left.
                    // This is a private non-static method because it changes the member variable p
            d = '?';
            if (p <= e.length() - 1) {
                d = e.charAt(p); // the next character to the left
            }
        } while ((p <= e.length() - 1) && (((d <= '9') && (d >= '0')) || (d == '_') || (d == '.')));// check for a valid
                                                                                                    // character
        if (flag == 1) {
            total = total / Math.pow(10, count * 1.0); // compute the value taking into account
                                                        // the number of decimal places
        }
        return total;
    }

标签: javaoopstackarithmetic-expressions

解决方案


推荐阅读