如何在Java解析器的扫描程序中获取下一个字符

如何在Java解析器的扫描程序中获取下一个字符,java,parsing,Java,Parsing,我不知道如何编写“下一个源字符”代码来查找字符串的下一个字符 public class scanner { protected char currentChar; protected StringBuffer currentSpelling; protected byte currentKind; private void take (char expectedChar){ if (currentChar == expectedChar){

我不知道如何编写“下一个源字符”代码来查找字符串的下一个字符

public class scanner {
    protected char currentChar;
    protected StringBuffer currentSpelling;
    protected byte currentKind;

    private void take (char expectedChar){
        if (currentChar == expectedChar){
            currentSpelling.append(currentChar);
            currentChar = next source character;
        }
    }


    private void takeIt(){
        currentSpelling.append(currentChar);
        currentChar = next source character;
    }

}

可能您需要定义您的字符源。在这里,我将其传递给Scanner的构造函数

public class Scanner {
    protected char currentChar;
    protected StringBuffer currentSpelling;
    protected byte currentKind;
    private Reader inputStreamReader;

    public Scanner(InputStream inputStream) {
        reader = new InputStreamReader(inputStream);
    }

    private void take (char expectedChar){
        if (currentChar == expectedChar){
            currentSpelling.append(currentChar);
            currentChar = (char) inputStreamReader.read();
        }
    }


    // Note. Probably you need to get the currentChar before append it.
    // So the order of operations should be inverted
    private void takeIt(){
        currentSpelling.append(currentChar);
        currentChar = (char) inputStreamReader.read();
    }

}
要创建它,您可以执行以下操作(或者替换它以从另一个流读取数据,例如文件):


注意:我将类的名称从
scanner
更改为
scanner
,因为将类大写是一种很好的做法。

使用for循环。使用String.charAt()方法的索引&就这样了。还有一个构造函数,它读取
currentChar
的第一个值。还有一些文件结束测试。美好的
Scanner myScanner = new Scanner(System.in);