2016-04-27 61 views
2

我不知道如何編寫「下一個源字符」代碼來查找字符串的下一個字符。如何在Java語法分析器的掃描器中取下一個字符

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; 
    } 

} 
+0

使用for循環。使用索引* String * .charAt() - 方法&你去。 – Seth

回答

1

可能您需要定義您的字符來源。在這裏我將它傳遞給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 myScanner = new Scanner(System.in); 

注:我改的名字從scannerScanner的班級,因爲擁有班級資本化是一種很好的做法。

+0

和一個讀取'currentChar'的第一個值的構造函數。還有一些文件結束測試。尼斯。 –