Here’s what I’ve done:
while (sc.hasNext()) {
String sLine = sc.nextLine();
sLine.replaceAll("\\s", "");
String[] scanned = sLine.split("");
My input is going to be something like this:
IF (2 -2 +) (3 2 *) (-1 4 +) (5 3 *)
What this means is irrelevant, but what the scanner does is store it in a string “as is”, first of all. Then I use the replaceAll function to remove all whitespace. I am then left with:
IF(2-2+)(32*)(-14+)(53*)
I then interpret this code using java and perform the calculation if no errors occur. My issue now is, that when I split the string into tokens, it’s going to make each “minus” sign its own token, but I want to somehow relate it with the integer following it so that token is still just an integer (now negative) and have no tokens with a minus sign in it. Is there an easy way to do such a thing?
You can use
negative look-behindto split onempty stringnot preceded by ahyphen:-This will not split on the empty string between
-and2, thus keeping them intact.Output: –
Now you have
-2and-1instead of having-as separate element.