簡體   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