I have an arithmetic expression(a string) with unary operator, and I want to put each element in an array. For example: -3+4.2*5==>output should be: -3, +, 4.2 ,* , 5(not -,3,+,4.2, *, 5) 3+-5 ==> output should be: 3,+,-5(with the unary operator) (3/(5-8)+18)2==>output should be: (,3,/,(,5,-,8,),+,18,),,2
Here is the code I tried so far, and the output is 3,+,-,5, which didn't put the unary operator in the front of a digit.
My question is how to put each element properly in an array.
public class Test2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Input:");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
String[] arr1= splitInfixExpression(input);
for(int i=0;i<arr1.length;i++)
{
System.out.println(arr1[i]);
}
}
priva te static boolean isOperandChar(final char c) {
return Character.isDigit(c) || c == '.';
}
private static boolean isParenthesis(final char c) {
return c=='('||c==')';
}
private static String[] splitInfixExpression(final String input) {
final List<String> postfixExpression = new ArrayList<>();
boolean encounteredOperandStart = false;
String currentOperand = "";
for (final char c : input.toCharArray()) {
if (encounteredOperandStart) {
if (isOperandChar(c)) {
currentOperand += c;
}
postfixExpression.add(currentOperand);
postfixExpression.add(String.valueOf(c));
currentOperand = "";
encounteredOperandStart = false;
} else {
if (isOperandChar(c)) {
encounteredOperandStart = true;
currentOperand += c;
}
else if(isParenthesis(c)) {
postfixExpression.add(String.valueOf(c));
//currentOperand = "";
encounteredOperandStart=false;
}
else{
postfixExpression.add(String.valueOf(c));
//currentOperand = "";
encounteredOperandStart=false;
}
}
}
if (!currentOperand.isEmpty()) {
postfixExpression.add(currentOperand);
}
return postfixExpression.toArray(new String[postfixExpression.size()]);
}}