2017-09-17 157 views
0

我應該如何循環這個構造函數?參數從文本文件傳遞。我試過了一個while循環,但它甚至不讀取我的文本文件的第一行。我的文本文件包含ff: s0,a,s0,a,-1 (--next line--) s0,b,s0,b,-1。如果我不使用循環,它將獲取我的文本文件的內容,並將其傳遞給構造函數。
編輯:我已更正並標記爲循環的構造函數。如果我包含第二個while循環,它不會獲得文本文件的內容。構造函數的循環方法

Edit2:第一個while循環將我的文本文件的內容放入一個名爲argument的數組中。第二個while循環執行循環,將參數數組的內容傳遞給變量,然後將其傳遞給構造函數。這第二個while循環不起作用。

Scanner scanner = new Scanner(new File("D:\\Kirk\\Documents\\NetBeansProjects\\TuringMachine\\src\\turingmachine\\Algorithms.txt")); 
String data = scanner.nextLine(); 
String[] arguments = data.split(","); 
StringTokenizer st = new StringTokenizer(data); 
int i = 0; 
while (st.hasMoreTokens()) { //loop for putting contents of text file to array 
    arguments[i++] = st.nextToken(); 
}//end loop 


while(scanner.hasNextLine()){ //loop transition function(not working) 
    String fromstate = arguments[0]; 
    String read = arguments[1]; 
    String tostate = arguments[2]; 
    String write = arguments[3]; 
    int move = Integer.parseInt(arguments[4]); 
    trans.add(new Transition(new StateTapeSymbolPair(fromstate, read), new StateTapeSymbolPair(tostate, write),move)); 
    //loop the above constructor 
}//end while 
+0

這不是很清楚你在問什麼。哪個構造函數? 「循環構造函數」是什麼意思?編輯你的問題,並添加一些更多的細節,也許給你的代碼添加一些註釋,指出你的問題所涉及的部分。 – pvg

+0

好的,我編輯了代碼。我已經評論過哪些while循環有問題,我需要循環的代碼 – Kirk

+0

目前還不清楚你在問什麼。你是說內在的,而不是循環? – Kerry

回答

2

你沒有循環獲取eah線的數據。 這裏的一個例子:

Scanner scanner = new Scanner(new File("Algorithms.txt")); 

    while(scanner.hasNext()){ 

     String data = scanner.nextLine();  // your line   
     String[] arguments = data.split(","); // split the line 

     // getting data for each data inside the line 
       String fromstate = arguments[0]; 
       String read = arguments[1]; 
       String tostate = arguments[2]; 
       String write = arguments[3]; 
       int move = Integer.parseInt(arguments[4]); 

       System.out.println(fromstate+"-"+read+"-"+tostate+"-"+write+"-"+move); 

     } 
+0

謝謝!所以我的錯誤是我把我的字符串數據和參數數組放在一個單獨的數組中? – Kirk

+0

代碼中有一些錯誤。你得到文件的第一行,並根據「,」分隔符將這一行的每個數據放在一個數組中,然後用第一行值更新這個數組的第一個元素。最後你循環一個真實的條件來獲得這個數組的數據。你不會指向你想要分割的線。 – Enjy

相關問題