简体   繁体   中英

Replace a positive or negative decimal or integer next to another in brackets

How do I replace a positive or negative decimal or integer next to another in brackets using Java?

I'm making a calculator using Java, and I'm finding it difficult to handle brackets when they are in the following format:

(-x)(-y)
(x)(y)

Other combinations of positive or negative numbers work it's only when i have to brackets side by side with no multiplication symbol that my code isn't working for. If there is a simpler method using Java regex then I'd be happy to find out how. Any help is greatly appreciated! Here is my code for handling brackets so far

setExpression(exp);
while(exp.contains("(") && exp.contains(")")){
    int lastOpen = exp.lastIndexOf("(");
    int nextClose = lastOpen + exp.substring(lastOpen+1).indexOf(")") + 1;
    //first close bracket after the last open bracket
    //treats the bracket as a separate expression and so checks it's validity
    if(sameNoBrackets() != ""){
        return sameNoBrackets();
    }
    setExpression(exp.substring(lastOpen+1, nextClose));
    result = checkExpression();

    if(!result.equals("")){
        //if true then there is an error message so program stops there
        return result;

    }else{
        String newText = calculateResult();
        lastOpen = exp.lastIndexOf("(");
        nextClose = lastOpen + exp.substring(lastOpen+1).indexOf(")") + 1;

        String lastChar = "";
        String nextChar = "";

        if(lastOpen > 0){
            lastChar = String.valueOf(exp.charAt(lastOpen-1));
        }

        if(nextClose + 2 <= exp.length()){
            nextChar = String.valueOf(exp.charAt(nextClose+1));
        }

        if(lastChar != ""){
            if(!"+-/*".contains(lastChar)){
                newText = "*"+newText;
            }
        }

        if(!"+-/*".contains(nextChar)){
            newText = newText+"*";
        }

        exp = exp.replace(exp.substring(lastOpen, nextClose+1), newText);
        //removes the bracket and replaces with the appropriate replacement text
    }
}
setExpression(exp);
//checks the validty of the expression onces the brackets have been removed
result = checkExpression();
if (result == ""){
    //calculates the answer if there is no error
    result = calculateResult(); 
}
//returns either the answer or the error message that has been generated
return result;  

Take a look at the data structure Stack which enables you to resolve the term in more feasible chunks so that they can be calculated according to their priority. So the problem with multiplication can also be better resolved since you know that after closing bracket must come an operator if not then default multiply or end of term has reached.

In this way it is also possible to resolve nested terms and brackets since the stack enables you to resolve regular languages which at least is necessary to implement a calculator.

A simple workaround for the bracket problem is to preprocess your term literal and replace every occurrence of )( close and open brackets with )*( so that your parser must not handle the )( condition. But as EJP and Miho already say your implementation will not be able to handle all input variants.

The problem is actually that your entire technique is wrong.

You need to look up the Dijkstra shunting-yard algorithm, or recursive descent expression parsing.

You don't have to handle this as a special case at all: it just falls naturally out of a correct implementation.

You need to throw this away and start again.

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