Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting up a boolean expression in Java

How can I split a boolean expression in Java? For example, I want to get the following from the expression a_1 & b_2 | (!c_3):

String tokens[] = {"a_1", "&", "b_2", "|", "(", "!", "c_3", ")"};

The names of the variables contain alphanumeric characters and underscores (_).

like image 305
JaneNY Avatar asked Apr 23 '26 20:04

JaneNY


1 Answers

If you want to parse the String - maybe to create a syntax tree and evaluate the expression -, then it's better to parse the String with a simple switch expression:

// for each char c in String
switch (c) {
  case '&': processAnd();break;
  case '|': processOr();break;
  case '!': processNot();break;
  case '(': processOpenPara();break;
  case ')': processClosePara();break;
  case ' ': break;
  default:  processVarName(); break;
}

This is just a stub to show the pattern. You may want to use a stack to evaluate the expression.

like image 144
Andreas Dolk Avatar answered Apr 25 '26 10:04

Andreas Dolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!