Mani firoozi
Mani firoozi

Reputation: 33

Finding numbers inside parentheses

as a part of my project i need to to be able to add the numbers inside these parentheses,i have been working on it for too long but no result, i would appreciated any help

String[] s = "1 2 3 ( 4 5 6 ) * 1000 7 8".split("\\s");

for example in this case there are 3 numbers

This is what I have so far:

while(st.hasMoreTokens()) {
    if ( st.nextToken() != "(" )
        count = count +1 ;
}
if ( st.nextToken() == "(" )
    while (st.nextToken() != ")") {
        count2 = count2 + 1;
    }
System.out.println(count); System.out.println(count2);
}

Upvotes: 2

Views: 167

Answers (2)

jjjt78
jjjt78

Reputation: 13

If you want to keep track of the parentheses and evalute your string as an equation, you might want to look at the Shunting-yard algorithm.

Upvotes: 1

swapz83
swapz83

Reputation: 422

Didn't quite get the use case here. Assuming you are always going to have only one set of paranthesis [ "(" and ")" ], there will never be a paranthesis mismatch and you don't care about the other numbers / digits / operators outside the paranthesis, the easy way to add the numbers between paranthesis would be

String mainStr = "1 2 3 ( 4 5 6 ) * 1000 7 8";
String []inside = mainStr.substring(mainStr.indexOf("(")+1, mainStr.indexOf(")")
                  .split("\s");
int sum = 0;
int innerNum = 0;
for (int i=0; i<inside.length;i++) {
    try {
        innerNum = Integer.parseInt(inside[i]);
    } catch (NumberFormatException e) {
        innerNum = 0;
    }
    sum = sum + innerNum; 
}
return sum;

For multiple sets of paranthesis (which are not nested), we can loop over mainStr to get the next set, and proceed in same manner

Upvotes: 2

Related Questions