开发者

Read a file in specific format into ArrayList

开发者 https://www.devze.com 2023-01-26 07:55 出处:网络
I have f开发者_开发知识库ile with this specific format: 0 2 4 0 1 A 0 5 B 1 1 A 1 3 B 2 6 A 2 4 B 3 6 A

I have f开发者_开发知识库ile with this specific format:

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  
  • line 1 = start state
  • line 2 = accept state
  • line 3 - n = transition table
  • 1st row = state in
  • 2nd row = state out
  • A,B = symbol

How can my FileReader in Java read these file into 5 different ArrayLists (start state, final state, state in, state out and symbol)?


It's best to use a Scanner here:

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


You can use the Scanner class to read the file (nextLine() is highly recommended). Since you know the positions of the items you need, you can then use the split method to parse the input string in what ever ArrayList you like.


Have a look at the StringTokenizer, use ArrayLists to build up your lists.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号