0

Im doing a calculator for schoolwork and everything works except my scanner, cause when it takes a negative integer it doesnt see it as a negative number it just sees the subtraction sign as a operator and I want it to see it like a part of the operand:

String exp = "8+4*-12-4";
    String[] temp = new String[exp.length()];
    temp =exp.split("(?<=[-+*/])|(?=[-+*/])");

this makes it correct if its only positive integers. for example input: 8+4*12-4 and the output:[8, 4, 12, *, +, 4, -]

but with a negative number it doesnt get it right! so thats what I want help with, thanks in advance

JohnBanana
  • 45
  • 6

1 Answers1

0

LinkedList <String>list= new LinkedList<String>(); just takes each of the characters in the string and adds each to the resulting list. Instead of doing this, you need to write syntax-aware code. If you can insist on white space between all tokens, then you can split on spaces with, for example, String.split. If not, the simplest alternative is to iterate over the characters in the string "by hand" and create the output that way.

While I suppose it is also possible to use String.split with a non-capturing positive lookahead to also split on operators, figuring out regular expressions to that level of mastery is more difficult than solving the problem in code. I can't give an example for the positive lookahead assertion implementation, as I don't want to take the time to run up a development envirionment, write the code, create test cases and debug it - since I don't think this is the approach you should take in any case.

Community
  • 1
  • 1
James Youngman
  • 3,623
  • 2
  • 19
  • 21
  • could you give me an example on how you could use split in this case? Ive been googling but cant really find a good example, thanks in advance – JohnBanana Apr 24 '16 at 10:00