문제

I have file 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)?

도움이 되었습니까?

해결책

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.

다른 팁

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top