I am writing my first calculator. I want to break a string of numbers and signs into 2 collections.
I enter the following code:

protected static String Go (String s) { ArrayList <String> Numbers = new ArrayList <String> (); ArrayList <String> Simbols = new ArrayList <String> (); for (String c1 : s.split("[^0-9]+")) Numbers.add(c1); for (String c2 : s.split("[0-9]+")) Simbols.add(c2); 

When testing produces a variety of results, for example:

  1. s="6-6" I get:

     Numbers=[6, 6] Simbols=[, -] 
  2. s="+6+6" I get:

     Numbers=[, 6, 6] Simbols=[+, +] 
  3. s="+6+6" I get:

     Numbers=[, 6, 6] Simbols=[+, +] 

That is, for some reason, an empty element is placed at the beginning of the Simbols or Numbers collection. Because of this, I can not do anything further.

    3 answers 3

    String.split() too limited even for a simple calculator. I would suggest using regular expressions with named groups. It will be convenient to parse the string.

    Here is a good article for your problem: Single-line calculator, art or vice?

    Additional links:

    Java string processing Part II: Pattern, Matcher

    Pattern. Features for describing regular expressions

      Those. For some reason, an empty element is placed at the beginning of the Simbols or Numbers collection.

      Because the line starts with either a digit or a non digit. And this symbol will serve as part of the separator in one of the splits. Well, what is between it and the beginning of the line? An empty string is sent to one of the results.

      PS: And the calculator still does not work: +6+-7 . Break into string tokens and then process them individually.

        If you do not touch the regular degeneration, you can implement through the reverse Polish entry , an example from my repository