Java 识别标记

标签 java arraylist token

我正在做一项作业,我必须查看文件并识别标记。我认为我走在正确的道路上。我已经完成了大部分工作,但我在识别特定字符时遇到了困难,因此我可以选择在识别 token 时忽略它。它是 \n 我得出这个结论是因为当我尝试在 if 语句中执行 tokens.get(6).equals('\n') 时,它出现了up as false 就好像它不是 \n 我无法识别此数组索引值中存储的内容。文本文件如下所示

编辑:我知道它是 \n 因为我做了 System.out.println("ddd"+ tokens.get(6) +"dddd") 和输出是 ddd 然后是一个新行和 dddd

编辑2:我添加了System.out.println(", unidentified "+ word);这是输出 enter image description here

read a
read b
c := a + b + 3
write c 

输出应该是这样的

<read>, read
<id>, a
<read>, read
<id>, b
<id>, c
<assign>, :=
<id>, a
<add_op>, +
<id>, b
<add_op>, +
<number>, 3
<write>, write
<id>, c 

我的输出看起来像这样

<read>, read
<error>, unidenfified
<error>, unidenfified
<assign>, :=
<id>, a
<add_op>, +
<id>, b
<add_op>, +
<error>, unidenfified
<error>, unidenfified

我不确定为什么会发生这种情况。 我的代码:

import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
import java.lang.Character;

public class Tokens {

    public static void main(String[] args) throws IOException {

        Scanner input = new Scanner(System.in); // Scanner for taking input from
                                                // the user

        String fileName;
        System.out.println("Enter the name of the file.");
        fileName = input.next();

        fileExists(fileName); // Checks to see if the file exists

        ArrayList<Character> arrayOfTokens = new ArrayList<Character>();
        ArrayList<String> assembled = new ArrayList<String>();
        readToArray(arrayOfTokens, fileName);
        assembled = assembleTokens(arrayOfTokens);

        for(int i = 0; i < assembled.size(); i++) {
             analyze(assembled.get(i));
         }

    }

    /*
     * readToArray goes through a file and adds all its elements in individual
     * character form. It is stored into an arraylist and it is then returned
     * 
     * @param storeChar: This is an arraylist of characters that the characters
     * will be saved into and then returned.
     * 
     * @param fileName: The filename that you want to take the data from.
     */
    private static ArrayList<Character> readToArray(
            ArrayList<Character> storeChar, String fileName) throws IOException {
        /*
         * Block of code to setup the fileInput stream to take in data from the
         * file. Reads character by character and stores into an arraylist. int
         * atChar: the current character the reader is at. Returns in int format
         * (Need to be converted to character later on) int currentIndex: to add
         * a character to an index. Increments until no more characters are left
         */
        FileInputStream fileInput = new FileInputStream(fileName);
        int atChar;
        int currentIndex = 0;

        /*
         * Loop to go through and add the converted character from an int to the
         * arraylist. Loops until atChar returns -1 which means no more
         * characters in file.
         */
        while ((atChar = fileInput.read()) != -1) {
            storeChar.add(currentIndex, (char) (atChar));
            currentIndex++;
        }
        fileInput.close();

        return storeChar;
    }

    /*
     * fileExists method makes sure the file the user enters exists in the
     * system. If it doesn't then the program will terminate before any further
     * code is executed.
     * 
     * @param fileName: Takes in a string paramater of the file name that you
     * want to if it exists.
     */
    private static void fileExists(String fileName) {

        boolean ifExists; // Boolean statement that will later be set to the
                            // value of whether the file exists or not

        File file = new File(fileName);
        ifExists = file.exists();

        if (ifExists == false) {
            System.out
                    .println("Unable to find the file. Will now close the program.");
            System.exit(0);
        }
    }

    private static ArrayList<String> assembleTokens(ArrayList<Character> tokens) {

        ArrayList<String> identified = new ArrayList<String>();
        int counter = 0;
        String concatinated = "";

        while (counter < tokens.size()) {
            if (!tokens.get(counter).equals(' ')) {
                concatinated += tokens.get(counter);
                counter++;
            } else {
                identified.add(concatinated);
                concatinated = "";
                counter++;
            }
        }

        return identified;
    }

    private static void analyze(String word) {
        if(word.equals("read")) {
            System.out.println("<read>, read");
        } else if(word.equals("write")) {
            System.out.println("<write>, write");
        } else if(word.equals(":=")) {
            System.out.println("<assign>, :=");
        } else if(word.equals("(")) {
            System.out.println("<lparen>, (");
        } else if(word.equals(")")) {
            System.out.println("<rparen>, )");
        } else if(word.equals("+") || word.equals("-")) {
            System.out.println("<add_op>, " + word);
        } else if(word.equals("*") || word.equals("/") || word.equals("//") || word.equals("%")) {
            System.out.println("<mult_op>, " + word);
        } else if(word.matches("[a-z]+[A-Za-z0-9]*")) {
            System.out.println("<id>, " + word);
        } else if(word.matches("\\d+(\\.\\d+)?")) {
            System.out.println("<number>, " + word);
        } else {
            System.out.println("<error>, unidenfified");
        }

    }
}

最佳答案

简单地过滤掉\n读取文件时

 if (atChar != '\n') {
     storeChar.add(currentIndex, (char) (atChar));
 }

或者你可以使用

fileInput.readLine()

然后对字符串进行标记

编辑

查看一下您上次的编辑,如果做 readLine 会更好然后使用 String.split(" ");获取您的代币

关于Java 识别标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248289/

相关文章:

java - MongoDB 使用分层 JSON 进行更新 - 如何高效?点符号?

ruby-on-rails - 使用 Devise token 登录,这是内置的吗?

Firebase 刷新 token 过期

java - 从 HTML 网页读取 URL 并将其写入文件

java - 从父类(super class)创建 ArrayList 但包含扩展类的对象

proxy - 使用 RBAC 访问 kubernetes 仪表板所需的用户权限

java - Hadoop上出现UnsupportedClassVersionError,版本没有明显变化

java - 检查 Boolean.TRUE/Boolean.FALSE 是否可以避免装箱/拆箱?

java - 为什么特定日期 (03/12/2018) 之间的差异不是确切的天数?

java - Java中获取arrayList中重复值的计数而不影响arrayList的顺序