tags:

views:

168

answers:

4

hi, i am confused on why it doest not split the string? my array of string exp does not contain anything when i debug it is the split wrong?what i am trying to do is to split a very simple expression like 1+2+3 and then parse the values, doing a calculator.

EDIT hi, why i am splitting on each character is because i am doing a calculator, and have read something about converting infix to postfix,so i need to split the string and then loop through each of the string and do the checking as shown below,however when i debug it shows the exp[] is empty

For each token in turn in the input infix expression:

    * If the token is an operand, append it to the postfix output.
    * If the token is an operator A then:
          o While there is an operator B of higher or equal precidence than A at the top of the stack, pop B off the stack and append it to the output.
          o Push A onto the stack.
    * If the token is an opening bracket, then push it onto the stack.
    * If the token is a closing bracket:
          o Pop operators off the stack and append them to the output, until the operator at the top of the stack is a opening bracket.
          o Pop the opening bracket off the stack.

When all the tokens have been read:

    * While there are still operator tokens in the stack:
          o Pop the operator on the top of the stack, and append it to the output.


   // the main class
public class Main {


    public static void main(String[] args) {
       calcExpChecker calc = new calcExpChecker("1+2+3+4");
       calc.legitExp();
       calc.displayPostfix();
    }

}
//the class
package javaapplication4;
import java.util.*;


public class calcExpChecker {


    private String originalExp; // the orginal display passed
    private boolean isItLegitExp; // the whole expression is it legit
    private boolean isItBlank; // is the display blank?
    private StringBuilder expression = new StringBuilder(50);
    private Stack stack = new Stack();//stack for making a postfix string

    calcExpChecker(String original)
    {
        originalExp = original;
    }

     //check for blank expression
    public void isitBlank()
    {
        if(originalExp.equals(""))
        {
            isItBlank = true;
        }
        else
        {
            isItBlank = false;
        }

    }

    //check for extra operators
    public void legitExp()
    {
      String[] exp = originalExp.split(".");
      for(int i = 0 ; i < exp.length ; i++)
      {
          if(exp[i].matches("[0-9]"))
          {
              expression.append(exp[i]);
          }
          else if(exp[i].matches("[+]"))
          {
             if(stack.empty())
             {
                 stack.push(exp[i]);
             }
             else
             {
                 while(stack.peek().equals("+"))
                 {
                    expression.append(stack.pop());
                 }
                 stack.push(exp[i]);
             }
          }
        if (!stack.empty())
        {
            expression.append(stack.pop());
        }
      }

    }

    public void displayPostfix()
    {
        System.out.print(expression.toString());
    }
}
A: 

Confession:

Okay I guess my answer is bad because there are subtle differences between Java and C# with this stuff. Still, maybe it'll help someone with the same problem but in C#!

Btw, in C#, if you pass in a RegEx "." you don't get an empty array, instead you get an array of blanks (""), one for each character boundary in the string.

Edit

You can pass a regex expression into the split() function:

string expressions = "10+20*4/2";

/* this will separate the string into an array of numbers and the operators;
   the numbers will be together rather than split into individual characters
   as "" or "." would do;
   this should make processing the expression easier
   gives you: {"10", "+", "20", "*", "4", "/", "2"} */
foreach (string exp in expressions.split(@"(\u002A)|(\u002B)|(\u002D)|(\u002F)"))
{
  //process each number or operator from the array in this loop
}

Original

String[] exp = originalExp.split(".");

You should get at least one string from the return value of split() (the original un-split string). If the array of strings is empty, the original string was probably empty.

JohnB
He's creating a calculator. I'd imagine that those operators are mandatory to know in the loop as well. Splitting on them would make this information lost in the result (your example would end up in `[1, 2, 3]`, not in `[1, +, 2, -, 3]`).
BalusC
Yes I realize that, but his original question was why is the array empty after the split()
JohnB
BalusC: The above code example will not lose the operators.
JohnB
It also isn't java ;)
Affe
ok, I'm not sure exactly how to do escape chars in Java or the unicode, but that should be trivial to fix.
JohnB
+1 Affe. Thanks, you are right, but I at least I feel like I learned something.
JohnB
A: 

why do you need to split on each character & rather not go for foreach character in the String. That way you don't have to reference as exp[i] either.

Anyways you can split using "" instead of "."

loxxy
Whether to use a `for` loop or a `foreach` loop has nothing to do with his problem, but I'd opt for the `foreach`
JohnB
I meant if he really wanted to loop over each letter then why spit it at all......Anyways I guess delimiting each character is better if he knows what each delimiter would be, considering that he is gonna make a calcy with known sorts of operators in between.
loxxy
+2  A: 

You want to split on every character, so rather use string.split("").

for (String part : string.split("")) {
    // ...
}

Or better, just iterate over every character returned by string.toCharArray().

for (char c : string.toCharArray()) {
    // ...
}

With chars you can use a switch statement which is better than a large if/else block.

BalusC
hi, i have converted it to a char[] before however the char does not contain a .matches method so i didnt continue working on a char[], however i have not gone through using a switch statement, i will look in that now. thanks
kyrogue
A `char` is indeed not a `String`. You can just use switch `case` statements or numeric operators like `>`, `>=`, `<`, `<=`, `==` and so on or even the methods provided by `java.lang.Character` to test the individual characters, for example `if (Character.isDigit(c))` if you want to test `0-9`. Also see http://download-llnw.oracle.com/javase/tutorial/java/data/characters.html and http://java.sun.com/javase/6/docs/api/java/lang/Character.html
BalusC
thanks! i have read before about the wrapper classes, but do not know it contains such methods
kyrogue
+2  A: 

If you make every character a delimiter, what is between them? Nothing

e.g., 1+2+3+4 is 1 a delimiter? yes, ok, capture everything between it and the next delimiter. Next delimiter? +. Nothing captured. Next delimiter? 2. etc etc

Affe
+1 so far the only one to answer the OP's question.
Jim Garrison
yes i got it, then how can i work around it? to split each of the operator and operand into the exp[]?
kyrogue
@kyrogue: I've answered that.
BalusC