2015-09-19 59 views
1

我正在編寫Java自定義語言的Java編程語言閱讀器的原始版本,並且我想找到最簡單的方法來打印位於兩個之間的ArrayList的元素內容雙引號元素。下面是源代碼:文本文件的在兩個雙引號之間的ArrayList中檢查元素

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
import java.util.ArrayList; 

public class PrimitiveCompiler { 

    public static ArrayList<String> toks = new ArrayList<String>(); 

    public static void main(String[] args) throws FileNotFoundException { 
     String content = readFile("C:\\program.txt"); 

     tokenize(content); 
    } 

    public static String readFile(String filePath) throws FileNotFoundException { 
     File f = new File(filePath); 
     Scanner input = new Scanner(f); 

     StringBuilder b = new StringBuilder(); 

     while (input.hasNextLine()) { 
      b.append(input.nextLine()); 
     } 

     input.close(); 

     return b.toString(); 
    } 

    public static ArrayList<String> tokenize(String fContent) { 
     int i = 0; 
     String tok = ""; 

     String contents = fContent.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", ""); 

     for(int a = 0; a <= contents.length() - 1; a++) { 
      tok += contents.charAt(a); 
      i = a; 

      if(tokenFinderEquals(tok, "WRITE")) { 
       toks.add("WRITE"); 
       tok = ""; 
      } 
     } 

     System.out.println(toks); 

     return null; 

     } 

    public static boolean tokenFinderEquals(String s1, String s2) { 
     if(s1.equalsIgnoreCase(s2)) { 
      return true; 
     } 

     return false; 
    } 
} 

內容現在只是WRITE,它成功地找到它,並把它添加到ArrayList中。我想要做的是計算雙引號,並在ArrayList中找到兩個雙引號以打印出它們之間的每個元素。它是否可以或有另一種更簡單的方法來做到這一點?提前致謝!

回答

1

您需要某種狀態來跟蹤您是否處於報價範圍內。例如:

boolean inQuote = false; 
for (int a = 0; a <= contents.length() - 1; a++) { 
    char c = contents.charAt(a); 
    if (c == '"') { 
    // Found a quote character. Are we at the beginning or the end? 
    if (!inQuote) { 
     // Start of a quoted string. 
     inQuote = true; 
    } else { 
     // End of a quoted string. 
     inQuote = false; 
     toks.add(tok); 
     tok = ""; 
    } 
    // Either way, we don't add the quote char to `tok`. 
    } else { 
    tok += c; 
    if (!inQuote && tokenFinderEquals(tok, "WRITE") { 
     // Only look for "WRITE" when outside of a quoted string. 
     toks.add(tok); 
     tok = ""; 
    } 
    } 
} 

儘管如此,使用這樣一個簡單的循環會開始變得困難。你可能想看看寫一個recursive descent parser