2015-11-03 70 views
-1

我需要將CSV文件的每一行轉換爲分離的堆棧(每行一個堆棧)。我的問題是在我掃描每行並將CSV轉換爲堆棧之後,我應該在哪裏存儲堆棧?我不知道我要創建多少堆棧,所以我需要一個動態數據結構來存儲創建的堆棧。以下是我的代碼。我可以將堆棧添加到ArrayList(或鏈接列表)嗎?

Scanner scanner = new Scanner(new FileReader(filepath)); 
Stack<String> st = new Stack<String>(); 
String line;   
     while (scanner.hasNextLine()){ 
          line = scanner.nextLine(); 
          List<String> items = Arrays.asList(line.split(":",-1)); 
          String x=items.get(0); 
     while(x == null || x.equals("#")) 
         { 
         line = scanner.nextLine(); 
         items=Arrays.asList(line.split(":",-1)); 
         x=items.get(0); 
         }` 

      st.addAll(items); 
      //i need to store st into a data structure before i clear it. 
      st = new Stack<String>(); 
      } 
+0

你問是選擇一個'ArrayList'還是'LinkedList'?或者你問一般來說是否可以有一個堆棧列表? – RealSkeptic

+1

你爲什麼不試試?是什麼讓你覺得你不能將堆棧存儲到列表中? –

+3

'List > stackList = new ArrayList >()'是你似乎在尋找的東西。 – ritratt

回答

-1

請指定您的語言以及您正在使用的庫。 但是縮進代碼更重要。 這就是我以爲你在反正以後:

Scanner scanner = new Scanner(new FileReader(filepath)); 
List<Stack<String>> st = new List<Stack<String>>(); 
String line;   
while (scanner.hasNextLine()) 
{ 
    line = scanner.nextLine(); 
    List<String> items = Arrays.asList(line.split(":",-1)); 
    String x = items.get(0); 

    if (x != null && !x.equals("#")) 
     st.add(items); 
} 

我可以告訴沒有必要爲具有不可過大文件,如超過50 MB,當至少一個「動態數據結構」。

+0

但是,我需要將st值存儲到另一個地方(或類)供以後使用。 –

+0

然後你可以使用你的st來完成這些代碼。 –

0

這是你正在尋找的實現:

   String line;   
       while (scanner.hasNextLine()){ 
            line = scanner.nextLine(); 
            List<String> items = Arrays.asList(line.split(":",-1)); 
            String x=items.get(0); 
       while(x == null || x.equals("#")) 
           { 
           line = scanner.nextLine(); 
           items=Arrays.asList(line.split(":",-1)); 
           x=items.get(0); 
           }` 

        st.addAll(items); 
        stackList.add(st); 

        //i need to store st into a data structure before i clear it. 
        st = new Stack<String>(); 
        } 

但是,不建議,這是有可能通過簡單的谷歌搜索或一點基本的研究來解決這些問題的平臺。

相關問題