pac bell pac bell - 1 month ago 9
Java Question

What's the while loop within the ExpressionTokenizer for in an ExpressionCalculator?

Hello this is part of a simple ExpressionCalculator java code. I don't seem to understand why the while loop is needed. Could someone explain its function to me?

The full code: https://github.com/yuxiaosun/Big-Java-Late-Objects/tree/master/13-Recursion/expressions

public class ExpressionTokenizer {
private String input;
private int start;
private int end;

public ExpressionTokenizer(String input) {
this.input = input;
this.start = 0;
this.end = 0;
this.nextToken();
}

public String peekToken() {
if (this.start >= this.input.length()) {
return null;
} else {
return this.input.substring(this.start, this.end);
}
}

public String nextToken() {
String r = this.peekToken();
this.start = this.end;

if (this.start >= this.input.length()) {
return r;
}

if (Character.isDigit(this.input.charAt(this.start))) {
this.end = this.start + 1;

**while (this.end < this.input.length() &&
Character.isDigit(this.input.charAt(this.end))) {
this.end += 1;
}**
} else {
this.end = this.start + 1;
}

return r;
}
}

Answer Source

What it does is make sure that the token will return all digits that follow as one token:

public static void main(String[] args) {
    ExpressionTokenizer et = new ExpressionTokenizer("123 + 5 + 4");
    while(et.peekToken() != null) {
        System.out.println(et.nextToken());
    }
}
//tokens are 123, +, 5, +, 4

Without the loop, it would not find 123, but just 1. That's all it does.