Storing contents of a webtable in a 2d matrix - java

I am trying to get the contents of a webtable using selenium and then store the contents in a 2d matrix.
Below is my code :
//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();
}
This gives me a Null Pointer Exception at "reportMatrix[i-2][j-1] = text".
I don't understand what I am doing wrong. Do I have to give even the second index when I declare the 2d array ?
Thanks in advance.

Unless you're a student who is studying multi-dimensional arrays, or you are otherwise constrained by an API you're required to use, just avoid arrays. You'll stay saner longer :)
If you HAVE to use a 2D array, it's wise to remember that you are not actually creating a matrix. You are creating a 1D array, and each element of this array is another 1D array. When you think of it that way, it becomes clear that you definitely have to initialize the "columns" arrays as well as the "rows" array.
This line:
String[][] reportMatrix = new String[rowCount-1][];
will initialize report matrix to have rowCount - 1 rows, and null for each and every set of columns.
Inside your first loop, after you have identified the number of columns, you want to do something like so:
reportMatrix[i] = new String[columnCount];
for(int j=1;j<=columnCount;j++) ...
This will allow you to have different number of columns in each row, if necessary.
Then, in your print loop, you should use the array lengths to print out the rows and columns. Remember to subtract 1 from the length attribute, since the this represents the number of elements in the array, and we almost always use zero-indexed for loops.
//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();
}

Related

Storing Values to a 2 dimensional array in Java

Brand new to Java.
I'm trying to store values from a String to a 2D array in java. The first two values of my String give me rows and columns for a grid. From here, I need to use Integer.parseInt() to parse the values and assign them. I'm attempting do this using a for() loop, but I'm completely stuck. Here's what I have so far (notes included to indicate what I'm attempting to acheive):
int r = Integer.parseInt(tokens[0]);
rows = r;
int c = Integer.parseInt(tokens[1]);
cols = c;
// create 2D array of int values
// place the reference to the array object in grid variable
int[][] input = new int[rows][cols];
grid = input;
//parse then store remaining values as int values in the 2D array using a nested loop
for(int i = 0 ; i < tokens.length ; i++) {
// read the next value and assign to next token
}
Your code seems to be a bit off - you parse those numbers into int variables r and c but then do int[][] input = new int[rows][cols];. You don't have such variables as rows and cols.
Also you should not start with 0 in your loop since values tokens[0] and tokens[1] are for row and column counts.
Start loop at 2, or end it with tokens.length-2 and add 2 every time you take value from tokens inside the loop.
In order to calculate the row and column index you need to take your i (e.g. index in tokens array), adjust for the aforementioned offset of 2, floor-divide by column count to receive row number, and get a remainder of division by column count to get row number.
E.g.
for(int i = 2 ; i < tokens.length; i++) {
int value = Integer.parseInt(tokens[i]);
int idx = i-2;
int row = Math.floorDiv(idx, c);
int col = idx % c;
grid[row][col] = value;
}

Adjusting 2 dimensional array's?

I made a 2 dimensional array like this:
char Grid[][] = {
{'#','#','#'}
{'#','#','#'}
{'#','#','#'}
}
and displayed it with this:
for (int row = 0; row < Grid.length; row++) {
for (int column = 0; column < Grid[row].length; column++) {
System.out.print(Grid[row][column]);
}
System.out.println();
}
I want to be able to simple adjust the elements in the array, like adding and removing elements. Since basic java (for some reason) doesn't seem to have any predefined functions to do this, i tried using the ArrayUtils class from common langs. I found a couple methods in the docs including "Add", "insert", and "remove" and tried something like this:
ArrayUtils.insert(Scene, Grid, 2); //(With "Scene" being the class name)
But as expected, it didn't work.
On another website, i read something about cloning the array, but i don't think this is the solution to my problem since i want to be able to move around an ASCII character, and i don't want to create a new array each time i move it.
EDIT: To be clear, i want to be able to either CHANGE the index value's or quickly remove then and place another on the exact spot.
arrays are basic types and are not used to add elements, for these operations ArrayList and depending if there is many inserts and deletes at any places LinkedList may be more convenient. ArrayUtils.insert should return a new array instance doing a copy of initial array.
Once created an array in java is with fixed length so in your case after you have used the Array Inicializer you end up with an array with length 3, having elements of type char array where each of them is with fixed length of 3 as well. To replace a given value all you need is to assign the new value to the proper indexes like :
Grid[i][j] = 'new character value';
As I've already said since the size is fixed you can not add new values to it, unless u copy the entire array in a new array of size (length +1) and place the new value on the desired position. Simple code demonstrating that:
private static void add(char[][] grid, int row, int column, char value) {
if (row < 0 || row > grid.length) {
throw new ArrayIndexOutOfBoundsException("No such row with index " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
if (column < 0 || column > grid[row].length) {
/*
* An array in Java is with fixed length so you should keep the index inside the size!
*/
throw new ArrayIndexOutOfBoundsException("Index " + column + " does not exists in the extended array!"); // you are trying to insert an element out of the array's bounds.
}
boolean flag = false; //indicates that the new element has been inserted.
char[] temp = new char[grid[row].length + 1];
for (int i = 0; i < temp.length; i++) {
if (i == column) {
temp[i] = value;
flag = true;
} else {
temp[i] = grid[row][i - (flag ? 1 : 0)];
}
}
grid[row] = temp; //assign the new value of the whole row to it's placeholder.
}
To remove an element from the array you would have to make a new array with size[length - 1], skip the element you would like to remove and add all the others. Assign the new one to the index in the matrix then. Simple code:
private static void remove(char[][] grid, int row, int column) {
if (row < 0 || row > grid.length) {
throw new ArrayIndexOutOfBoundsException("No such row with index " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
if (column < 0 || column > grid[row].length) {
throw new ArrayIndexOutOfBoundsException("No such column with index " + column + " at row " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
boolean flag = false; //indicates that the element has been removed.
char[] temp = new char[grid[row].length - 1];
for (int i = 0; i < temp.length; i++) {
if (i == column) {
flag = true;
}
temp[i] = grid[row][i + (flag ? 1 : 0)];
}
grid[row] = temp; //assign the new value of the whole row to it's placeholder.
}
If I define a method called print(char[][] grid) and put the code you use for printing then i'm able to do these tests:
add(Grid, 2, 3, '$'); //Add an element.
print(Grid);
System.out.println();
remove(Grid, 2, 0); // Remove an element.
print(Grid);
System.out.println();
Grid[0][0] = '%'; // Change an element's value.
print(Grid);
And the output is as follows:
###
###
###$
###
###
##$
%##
###
##$

Length of an Array

Ok so, you can create an array(EX: String[]) that holds a single value for each index by using length(), but that cannot be used for an array(EX: String[][]) that holds multiple values.
How would I pull the amount of indexes in the second mentioned array?
For 2d array
String[][] a=new String[4][5];
a.length // will give row count
a[0].length // will give column count of row 0 you can change the index for other columns
Demo
The same way:
String[][] aa = // ...
System.out.println("aa has " + aa.length + " indices");
for(int i = 0 ; i < aa.length ; ++i) {
System.out.println("aa[" + i + "] has " + aa[i].length + " indices");
}
To get the length of the array, you can do the same as you used to.
But if you want to get the amount of String objects, you can do something like this:
Stream.of(array).mapToInt(a -> a.length).sum()

Getting the length of two-dimensional array

How do I get the second dimension of an array if I don't know it? array.length gives only the first dimension.
For example, in
public class B {
public static void main(String [] main){
int [] [] nir = new int [2] [3];
System.out.println(nir.length);
}
}
See that code run live at Ideone.com.
2
How would I get the value of the second dimension of nir, which is 3?
which 3?
You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.
System.out.println(nir[0].length);
would give you the length of your first array.
Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).
int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
You can do :
System.out.println(nir[0].length);
But be aware that there's no real two-dimensional array in Java. Each "first level" array contains another array. Each of these arrays can be of different sizes. nir[0].length isn't necessarily the same size as nir[1].length.
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array
the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):
String row = "";
int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
for (int i=0; i<myArray.length; i++) {
row+="\n";
for (int j = 0; j<myArray[i].length; j++) {
row += myArray[i][j] + " ";
}
}
JOptionPane.showMessageDialog(null, "myArray contains:" + row);
nir[0].length
Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.
Assuming that the length is same for each array in the second dimension, you can use
public class B {
public static void main(String [] main){
int [] [] nir= new int [2] [3];
System.out.println(nir[0].length);
}
}
Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size.
so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.
Hope that helps..:)
Expansion for multi-dimension array total length,
Generally for your case, since the shape of the 2D array is "squared".
int length = nir.length * nir[0].length;
However, for 2D array, each row may not have the exact same number of elements.
Therefore we need to traverse through each row, add number of elements up.
int length = 0;
for ( int lvl = 0; lvl < _levels.length; lvl++ )
{
length += _levels[ lvl ].length;
}
If N-D array, which means we need N-1 for loop to get each row's size.
//initializing few values
int[][] tab = new int[][]{
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}
};
//tab.length in first loop
for (int row = 0; row < tab.length; row++)
{
//tab[0].length in second loop
for (int column = 0; column < tab[0].length; column++)
{
//printing one value from array with space
System.out.print(tab[row][column]+ " ");
}
System.out.println(); // new row = new enter
}

java 2d array arithmetic

Guys, I am struggling studying for exam with the 2d array of past exam paper. I have to write a method
sumr static (int[][] v)
that returns a 2d array consisting of 2 rows and the entries of the first row sums of v and the second row is the same of the first row of v. Eg:
a = {{2,3,3}, {1,3}, {1,2}}
the method returns 2d array
b = {{8,4,3},{2,3,3}}
I first try to make my method return a 2d array, but I was having the error illegal start of expression, now I have the following code, but the last element does not print and the elements a printed all in in line, not in a matrix way... Please guys help me, my exam is tomorrow.
public class Sum
{
// int[][] a = {{2, 3, 3}, {1, 3}, {1, 2}};
public void sumr(int[][] v)
{
for(int rows = 0; rows < v.length; rows++){
for(int columns = 0; columns < v.length; columns++){
int result = v[rows][columns];
System.out.print(result + " ");
//return [][] result;
}
}
}
public int getCount(int[][] Array)
{
int result = 0; //temp location to store current count
for (int i = 0;i <= Array.length -1;i++){//loop around first array
//get the length of all the arrays in the first array
//and add them onto the temp variable
result += Array[i].length;
}
return result;
}
}
In the outer loop (after the inner loop) include:
System.out.println(); // go to next line!
And check against the inner-array length!!
int[] innerArray = v[rows];
for(int columns = 0; columns < innerArray.length; columns++){
It is:
public void sumr(int[][] v)
{
for(int rows = 0; rows < v.length; rows++){
int[] innerArray = v[rows];
for(int columns = 0; columns < innerArray.length; columns++){
int result = v[rows][columns];
System.out.print(result + " ");
//return [][] result;
}
System.out.println(); // go to next line!
}
}
Once you can iterate:
You must construct a two-items array:
1st item: "summed array"
2nd item: the same as v[0]
You must build that result.
You must build the 1st item iterating over v. Like you are trying to do. For each row (outer loop) you will iterate over the row and sum its values. So after processing each row (after the inner loop) you will have the summed value. That value must be placed into the "summed array".
Next you can build directly the result array, assigning the built sum to its first place and v[0] to the second place.
But I'm not writing code yet to let you do it ;-)

Categories