简体   繁体   中英

Evaluating Expression in java

I am getting output impossible. but it must be possible. when i check at the editor it shows that that the case is always true ie last three cases of switch.

public String isPossible(String express) {
    char a = ' ';
    char b = ' ';
    boolean flag = true;
    Stack<Character> pile = new Stack<Character>();
    char [] array = express.toCharArray();
    for (int i = 0 ; i < array.length ; i++) {
        a = array[i];
        switch (a) {
            case '(':
                pile.push(a);
                break;
            case '{':
                pile.push(a);
                break;
            case '[':
                pile.push(a);
                break;
            case ')':
                b = pile.pop();
                if (b != '(' || b != 'X')
                    flag = false;
                break;
            case '}':
                b = pile.pop();
                if (b != '{' || b != 'X')
                    flag = false;
                break;
            case ']':
                b = pile.pop();
                if (b != ']' || b != 'X')
                    flag = false;
                break;
        }

    }
    if (flag == false || pile.size() % 2 != 0)
        return "impossible";
    else
        return "possible";
}

public static void main(String args[]) {
    Merge a = new Merge();
    System.out.println(a.isPossible("(())"));
}

Your logic is incorrectly using the || (or) operator. It is always true that b is not '(' or it's not 'X' . You want && (and).

Replace

if(b!='(' || b!= 'X')

with

if(b!='(' && b!= 'X')

and similarly for the other if conditions in the case statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM