I have a class where I have to print each token of a math expression. I have got my code to the point where it prints out everything except the numbers together. I am not sure what to fix in order to do that.
This is what the desired output is:
next token: [15]
next token: [*]
next token: [(]
next token: [26]
And this is what my code currently produces:
next token: [1]
next token: [5]
next token: [*]
next token: [(]
next token: [2]
etc...
Here is my code:
public class TokenIter implements Iterator<String> {
static int counter = 0;
private String line;
private String nextToken;
public TokenIter(String line) {
this.line = line;
}
public void remove() {
throw new UnsupportedOperationException();
}
public static void main(String[] args) {
String line = " 15*(26+37) - 443/7*612 - (233-543234) ";
System.out.println("line: [" + line + "]");
TokenIter tokIt = new TokenIter(line);
// print tokens in square brackets to check absence of white space
while (tokIt.hasNext()) {
if (tokIt.next() != "no")
System.out.println("next token: [" + tokIt.next() + "]");
counter++;
}
}
public boolean hasNext() {
if (counter < line.length())
return true;
else
return false;
}
public String next() {
String s = "";
if (!hasNext())
return null;
else {
char c = line.charAt(counter);
if (c == ('/')) {
counter = counter++;
s = "" + c;
return s;
}
if (c == ('+')) {
counter = counter++;
s = "" + c;
return s;
}
if (c == ('*')) {
counter = counter++;
s = "" + c;
return s;
}
if (c == ('-')) {
counter = counter++;
s = "" + c;
return s;
}
if (c == ('(')) {
counter = counter++;
s = "" + c;
return s;
}
if (c == (')')) {
counter = counter++;
s = "" + c;
return s;
} else if (c == ' ') {
counter = counter++;
return "no";
}
while (Character.isDigit(c)) {
counter = counter++;
s += "" + c;
return s;
}
}
return s;
}
}
I understand there are other ways to do this like a string tokenizer with delimiters, but I need to do it this way.