2016-03-25 16 views
0

セレンを使用してウェブテーブルのコンテンツを取得し、コンテンツを2次元マトリックスに保存しようとしています。以下はウェブテーブルの内容を2次元マトリックスに保存する

は私のコードです:

//Locate the webtable 
WebElement reportTable = driver.findElement(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]")); 

int rowCount = driver.findElements(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]/tbody/tr")).size(); //Get number of rows 
System.out.println("Number of rows : " +rowCount); 

String[][] reportMatrix = new String[rowCount-1][]; //Declare new 2d String array 
           //rowCount-1 because the first row is header which i don't need to store 

int mainColCount = 0; 


for(int i=2;i<=rowCount;i++) //Start count from second row, and loop till last row 
{ 
    int columnCount = driver.findElements(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td")).size(); //Get number of columns 
    System.out.println("Number of columns : " +columnCount); 

    mainColCount = columnCount; 

    for(int j=1;j<=columnCount;j++) //Start count from first column and loop till last column 
    { 
     String text = driver.findElement(By.xpath("//*[@id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td["+j+"]/div")).getText(); //Get cell contents 

     System.out.println(i + " " + j + " " + text); 

     reportMatrix[i-2][j-1] = text; //Store cell contents in 2d array, adjust index values accordingly 
    } 
} 


//Print contents of 2d matrix 
for(int i=0;i<rowCount-1;i++) 
{ 
    for(int j=0;j<mainColCount;j++) 
    { 
     System.out.print(reportMatrix[i][j] + " "); 
    } 
    System.out.println(); 
} 

これは私に "reportMatrix [I-2] [J-1] =テキスト" でNULLポインタ例外を提供します。

私は間違っていることを理解していません。 2次元配列を宣言するときに2番目のインデックスを与えなければなりませんか?

ありがとうございます。

答えて

0

多次元配列を学習している学生、または使用する必要のあるAPIによって制約されている場合を除き、配列を避けてください。

2次元配列を使用する必要がある場合は、実際に行列を作成していないことを忘れないでください。あなたは1D配列を作成しており、この配列の各要素は別の1D配列です。このように考えると、「列」配列と「行」配列を必ず初期化する必要があることが明らかになります。

この行: - 1行、およびそれぞれの列のすべてのセットの場合はnull

String[][] reportMatrix = new String[rowCount-1][]; 

はをrowCountを持つことが報告行列を初期化します。あなたの最初のループ内

、あなたは列の数を特定した後、あなたがそうのような何かをしたい:

reportMatrix[i] = new String[columnCount]; 

for(int j=1;j<=columnCount;j++) ... 

必要な場合、これは、あなたが各行の列の別の番号を持つことができるようになります。

次に、印刷ループで、配列の長さを使用して行と列を印刷する必要があります。 length属性から1を減算することを忘れないでください。これは、配列の要素数を表すため、ほとんどの場合、ゼロインデックス付きループを使用します。

//Print contents of 2d matrix 
for(int i=0; i < reportMatrix.length - 1; i++) 
{ 
    for(int j=0; j < reportMatrix[i].length - 1; j++) 
    { 
     System.out.print(reportMatrix[i][j] + " "); 
    } 
    System.out.println(); 
} 
+0

それは私の問題を解決しました。ありがとう! – sanaku

関連する問題