0
Stack<String> s = new Stack<String>();        
String[] tokens = infix.split(" ");

Right now I am making a calculator that accepts infix strings to calculate it, but they have to be separated by spaces, how do i make it where the postfix evaluator can accept no spaces. I.E. I have to do this

5 + 5 * sin ( 32 ) 

But I want it to accept that or

5+5*sin(32)
Deleted User
  • 2,551
  • 1
  • 11
  • 18
Jakkie Chan
  • 317
  • 4
  • 14
  • 1
    You should use a different strategy for tokenizing, not regular expressions. Like changes in the character classes (numeric, punctuations and related, letters). – Gábor Bakos Mar 30 '14 at 20:27
  • BTW, for experession evaluation there are many libs in Java that can handle that: http://stackoverflow.com/questions/1432245/java-parse-a-mathematical-expression-given-as-a-string-and-return-a-number – Gábor Bakos Mar 31 '14 at 05:46
  • Why? There's no need to prohibit spaces. Just scan your tokens properly. You have to do that anyway. – user207421 Feb 27 '17 at 00:12

2 Answers2

0

you can looping through the string and check the operators and insert a space after each operator and before and parentheses too looks like.

for( int i=0; i < infix.Length; i++){
    if(infix[i] == '*' || infix[i] == '-' ... ){
        infix.insert(" ", i -1 );
        infix.insert(" ", i +1 );
    }
}

or you can remover all spaces and split the string using regex with all operators and handle the parentheses in a special case.

Henka Programmer
  • 433
  • 6
  • 18
0

I'm not sure I understand what you want to achieve, but if you want to forbid whitespace characters in a JTexfield (this is what I understand by your question "accept no spaces"), here is how you can do:

yourTextField.setDocument(new PlainDocument() {
    final Pattern WHITE_SPACES = Pattern.compile("\\s+");


    public void insertString(int pOffs, String pStr, AttributeSet pA)
            throws BadLocationException {
        if (WHITE_SPACES.matcher(pStr).matches()) {
            return;  // whitespace characters not allowed
        }
    }
});
xav
  • 5,452
  • 7
  • 48
  • 57