繁体   English   中英

将特定格式的文件读入ArrayList

[英]Read a file in specific format into ArrayList

我有这种特定格式的文件:

0  
2 4   
0 1 A  
0 5 B  
1 1 A  
1 3 B  
2 6 A  
2 4 B  
3 6 A  
3 4 B  
4 6 A  
4 4 B  
5 1 A  
5 5 B  
6 6 A  
6 2 B
  • 第1行=起始状态
  • 第2行=接受状态
  • 第3行-n =过渡表
  • 第一行=状态为
  • 第二行=陈述状态
  • A,B =符号

我的Java FileReader如何将这些文件读入5个不同的ArrayList (开始状态,最终状态,状态输入,状态输出和符号)?

最好在这里使用扫描仪

static class State {
    int in;
    int out;
    String symbol;

    State(int in, int out, String symbol) {
        this.in = in;
        this.out = out;
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return in + " " + out + " " + symbol;
    }
}

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

    Scanner s = new Scanner(new File("input.txt"));

    int startState = Integer.parseInt(s.nextLine());
    List<Integer> acceptStates = new LinkedList<Integer>();
    List<State> states = new LinkedList<State>();

    Scanner st = new Scanner(s.nextLine());
    while (st.hasNextInt())
        acceptStates.add(st.nextInt());

    while (s.hasNextInt())
        states.add(new State(s.nextInt(), s.nextInt(), s.next()));

    System.out.println(startState);
    System.out.println(acceptStates);
    System.out.println(states);

    // logic...
}

您可以使用Scanner类读取文件( 强烈建议使用nextLine() )。 由于您知道所需项目的位置,因此可以使用split方法解析您喜欢的ArrayList中的输入字符串。

看一下StringTokenizer ,使用ArrayList来建立您的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM