2016-02-07 48 views
0

我試圖掃描一個文件併爲每一行創建一維數組,然後立即將該數組複製到二維數組的第一行。我已經讓我的代碼僅用於文件的第一行。它不會移動到下一行。它在遍歷整個2d數組時複製相同的行。我知道發生這種情況的原因是掃描下一行的計數器在到達2d數組末尾之前沒有增加。我如何增加掃描下一行的計數器?繼承人我的代碼:(tempString是在這個循環之前已經創建的一維數組)使用嵌套for循環將1d數組轉換爲2d數組

for(int i = 0; i < 7; i++){ 
     tempString = scnr.nextLine().split(" "); 
     //add lines to 2d array 
     for(int r = 0; r < 7; r++){ 
      int x = 0; //moves along each element in tempString 
      for(int c = 0; c < tempString.length; c++){ 
       temp[r][c] = Double.parseDouble(tempString[x]); 
       x++; 
      } 
     } 
    } 

回答

0

你有3個循環,但你只需要兩個。從文件中讀取的每個輸入行將成爲2-D陣列的一行:

for(int r = 0; r < 7; r++){ 
     tempString = scnr.nextLine().split(" "); 
     temp[r] = new double[tempString.length]; 
     for(int c = 0; c < tempString.length; c++){ 
      temp[r][c] = Double.parseDouble(tempString[c]); 
     } 
    } 
0

我不太確定自己需要什麼。但是我從問題中得出的結論是,你有一個文件,你需要將它分成一個二維數組,其中列應包含每行內的單個項目,每行應該在一個新行中。

我的建議是使用ArrayList,它將爲您處理動態長度。

見下面的例子:當其形成2D陣列中的程序,包含第一尺寸

說我有一個文件「的text.txt」包含這樣

abc def ghi 
jhl mnop qrs uv 
wx yz 

然後這裏的一些數據每行和第二維包含來自每行的標記。

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 

public class Split { 
public static void main(String args[]){ 
    ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>(); 

    columns.add(new ArrayList<String>());//Col 1 
    columns.add(new ArrayList<String>());//Col 2 
    columns.add(new ArrayList<String>());//Col 3 

BufferedReader br = null; 
try 
    { 
    br = new BufferedReader(new FileReader("src\\text.txt")); 
    String sCurrentLine; 
    int j=0; 
    while ((sCurrentLine = br.readLine()) != null) { 
    String sLine[] = sCurrentLine .split(" "); 
    for(int i = 0; i < sLine.length; i++) 
    { 
     columns.get(j).add(sLine[i]); 
    } 
    j++; 
    } 
    for(ArrayList<String> line:columns){ 
     for(String tokens:line) 
      System.out.println(tokens); 
     System.out.println(); 
    } 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 
} 

如果這不是你所需要的,請儘量與實例進一步可能的話闡述你的問題。

請注意,我使用空格(「」)來分割令牌,您可以用您正在使用的任何東西來替換它。我希望它有幫助:)