So I have a grid that is 6 by 7
char[][] grid = new char[6][7];
And is populated with blank spaces using this loop:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ' ';
}
}
I also have a char[] array that holds 'A's 'B's and blank spaces. For example ch[0] = B, ch[1] = A, ch[8] = " ".
And I am simply trying to populate each slot of the 2d array 'grid' with the contents of the char array one at a time.
I tried to use the same for loop with some changes to populate the grid but when I run it only populates the top row of my grid and I'm not sure why. I have tried to move the i++, and change the for loop parameters but nothing is working and I need help. This is how I am trying to do it:
int i = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ch[i];
i++;
}
}
If it helps to know I am getting the contents of ch[] from a .csv file and storing it in a char array. When I run this code as is, it perfectly populates the top row of my grid (first row) but then it does not do anything to the remaining rows.
I don't want to change the data types of anything, I know I can get this too work I just need some help.
String[][] array = {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
I want to remove the {"",""} elements from the array.
How can I do it in Java?
Remove?
You cannot change the size of an existing array.
If you want to create a new array with only these elements, count the length of each array, create a new array based on those lengths, add elements to the new array.
String[][] array= {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
//Assuming you want a 1-D array
int valuesPresent = 0;
for (int i = 0; i < arrray.length; i++) {
for (int j = 0; i < arrray[i].length; i++) {
if (array[i][j] != "") {
valuesPresent++;
}
}
}
//Now you know how many values are there, so initialize a new array of that size
String[] answer = new String[valuesPresent];
//Now add all the values to it
int index = 0;
for (int i = 0; i < arrray.length; i++) {
for (int j = 0; i < arrray[i].length; i++) {
if (array[i][j] != "") {
answer[index] = array[i][j];
index++;
}
}
}
To get a 2-d array, easy to understand:
//Just reordered input so we can understand better
String[][] array= {{"abcd","zxcs"}, //Row 0, col 0 = abcd and col 1 = zxcs
{"asdf",""}, //Row 1, col 0 = asdf and col 1 = ""
{"",""}}; //Row 2, col 0 = "" and col 2 = ""
//Counts how many columns have values(are not equal to "") in each row
int rowsWithValues = 0; //Counts how many rows have at least 1 value. Here, 2
for (int row = 0; row < arrray.length; row++) {
for (int col = 0; col < arrray[row].length; col++) {
if (array[row][col] != "") {
rowsWithValues++; //Since there's a col with value for this row
break; //If any one value has been found, no need to check other cols
}
}
}
//Now we know how many rows we need in the result array: 2 (row 2 has no values)
String[][] result = new String[2][];
//We need to add the 2 rows with values now
int arrayIndex = 0; //Points to next empty index in result[][]
for (int row = 0; row < arrray.length; row++) {
int colsWithValues = 0; //Cols with values for each row
for (int col = 0; col < arrray[i].length; col++) {
if (array[row][col] != "") {
colsWithValues ++; //Col with value found for this row
}
}
//Eg. For row 0, colsWithValues will be 2, since 2 cols have values(abcd, zxcs)
//We need to add these 2 cols as a single array to result
String[] currentRow = new String[colsWithValues]; //Will be 2 here for row 0
int rowIndex = 0; //Points to next empty column in currentRow[]
for (int col = 0; col < array[row].length; col++) {
if (array[row][col] != "") {
currentRow[rowIndex] = array[row][col];
}
}
//After this, for row 0, currentRow will be {abcd, zxcs}
//Just add it to our result
result[arrayIndex] = currentRol;
//After 1st iteration, result will be {{"abcd", "zxcs"}, {}}
//During 2nd iteration, arrayIndex == 1, currentRow == {"asdf"}
//On adding it to result[1], result will be {{"abcd", "zxcs"}, {"asdf"}}
To start with, don't compare two Strings for equality using == or !=, even for String Arrays:
if (array[i][j] != "") {
In the case above, it should be:
if (!array[i][j].equals("")) {
If you're not quite up to Streams yet then this is one way that might interest you:
public static String[][] removeNullStringRows(String[][] array) {
if (array == null || array.length == 0) {
return null;
}
int validCount = 0; // Row Index Counter for the new 2D Array
/* Find out how may rows within the 2D array are valid
(where the do not consist of Null Strings {"", ""}).
This let's you know how many rows you need to initialize
your new 2D Array to. */
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (!array[i][j].equals("")) {
validCount++;
break;
}
}
}
/* Declare and initialize your new 2D Array. This is
assuming the column count is the same in all rows. */
String[][] array2 = new String[validCount][array[0].length];
validCount = 0; // Used as an index increment counter for the new 2D Array
// Iterate through the supplied 2D Array and weed out
// the bad (invalid) rows.
for (int i = 0; i < array.length; i++) { // Iterate Rows...
for (int j = 0; j < array[i].length; j++) { // Iterate Columns
/* Does this row contain anything other than a Null String ("")?
If it does then accept the entire Row into the new 2D Array. */
if (!array[i][j].equals("")) {
// Retrieve all the columns for this row
for (int k = 0; k < array[i].length; k++) {
array2[validCount][k] = array[i][k];
}
// The above small 'for' loop can be replaced with:
// System.arraycopy(array[i], 0, array2[validCount], 0, array[i].length);
validCount++; // Increment our Row Index Counter for the new 2D Array
break; // Get out of this column iterator. We already know it's good.
}
}
}
return array2; // Return the new 2D Array.
}
To use this method you might do it this way:
// Your current 2D Array
String[][] array = {
{"abcd",""}, {"asdf",""}, {"",""},
{"",""}, {"",""}, {"",""}
};
// If the supplied 2D Array is null contains no rows
// then get out of here.
if (array == null || array.length == 0) {
return;
}
// Display the original 2D Array (array) in the Console window
System.out.println("The original 2D Array:");
for (int i = 0; i < array.length;i++) {
System.out.println(Arrays.toString(array[i]));
}
// Remove all rows that contain all Null String Columns.
// Make your Array equal what is returned by our method.
array = removeNullStringRows(array);
// Display the new 2D Array (array) in the Console window.
System.out.println();
System.out.println("The New 2D Array:");
for (int i = 0; i < array.length;i++) {
System.out.println(Arrays.toString(array[i]));
}
And your Console Window output should look like:
The original 2D Array:
[abcd, ]
[asdf, ]
[, ]
[, ]
[, ]
[, ]
The New 2D Array:
[abcd, ]
[asdf, ]
I am assuming here that, the nested array could be of any size not just of 2 elements.
Create a predicate that takes Stream<String> and checks if any element is not null and non-empty.
String[][] array= {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
Predicate<Stream<String>> arrayPredicate = element ->
element.anyMatch(ele ->Objects.nonNull(ele) && !ele.isEmpty());
Now stream over the original array and filter the inner array based on a predicate and collect it in a new array.
String[][] copyArray = Arrays.stream(array)
.filter(arr -> arrayPredicate.test(Arrays.stream(arr)))
.toArray(String[][]::new);
array = copyArray; // reassign to array
You can filter out all null and empty elements from this 2d array as follows:
String[][] array = {{"abcd",""},{"asdf",""},{"",""},{"",""},{"",""},{"",""}};
String[][] nonEmptyArray = Arrays.stream(array)
.map(row -> Arrays.stream(row)
// filter out 'null' elements and empty strings
.filter(e -> e != null && e.length() > 0)
// an array of non-empty strings or an empty
// array if there are no such strings
.toArray(String[]::new))
// filter out empty arrays
.filter(row -> row.length > 0)
// an array of non-empty arrays
.toArray(String[][]::new);
// output
System.out.println(Arrays.deepToString(nonEmptyArray)); // [[abcd], [asdf]]
private String[][] removeFromArray(String[][] source, String[] objToRemove) {
return Arrays.stream(source)
.filter(element -> !Arrays.equals(element , objToRemove))
.toArray(String[][]::new);
}
void example() {
final String[] empty = new String[]{"", ""};
String[][] array = {{"abcd", ""}, {"asdf", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}};
array = removeFromArray(array, empty);
}
Something like that should work
I'm trying to convert a two-dimensional array to a one-dimensional array in Java.
I cannot use any additional data structures, ArrayLists, collections etc. for temporary storage.
Only one array can be allocated - the one that will be returned from the method.
There are three tests with arrays inputed into the method to validate the program. Test one has a 2D array with 3 rows and columns, test two has a 2D array with 3 rows and 1 column, and test three is empty.
My current code is:
public static int[] twoDConvert(int[][] nums) {
int index = 0;
int[] combined = new int[nums.length*3];
if (nums.length == 0) return combined;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums.length; col++) {
combined[index] += nums[row][col];
index++;
}
}
return combined;
}
The first test works correctly, but for some reason the 2nd test throws ArrayIndexOutOfBoundsException (Index 1 out of bounds for length 1).
This occurs no matter how large or small the combined array length is.
How can I fix this?
We create a single Integer array with a length determines by the size method. Size takes the 2-dimensional array and finds the sum of all columns in each row and returns that sum. We check if the length is 0, and if so, we return. We then loop through all rows, followed by a loop through all columns in that row. We then assign the value at that row and column to that next index in the array. Unfortunately we can't do any math (to my knowledge) to determine the index based of row/column since they could be variable sizes.
public static int[] twoDConvert(int[][] nums) {
int[] combined = new int[size(nums)];
if (combined.length <= 0) {
return combined;
}
int index = 0;
for (int row = 0; row < nums.length; row++) {
for (int column = 0; column < nums[row].length; column++) {
combined[index++] = nums[row][column];
}
}
return combined;
}
private static int size(int[][] values) {
int size = 0;
for (int index = 0; index < values.length; index++) {
size += values[index].length;
}
return size;
}
Using apache.poi, I am trying to read an Excel sheet and using the below code, I am printing all the values inside Excel..
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
// Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
// Print Excel data in console
String location = (row.getCell(j).getStringCellValue()+ "");
System.out.println(location);
}
When I print the location System.out.println(location);, it prints my all Excel sheet data. I haven't any control over there. I am trying divide the value by the column.
Suppose I have 3 cells and I want to get a value like firstname[],lastname[],age[] so that I can do any operation by the indexing. I am not getting any solution.
Here is my full code
https://codeshare.io/anNwy3
Create a 2D String array. When iterating store the contents into the array
String[][] excelData = new String[numColumns][searcsheet.getLastRowNum()];
//numColumns is the number of columns in the excel sheet.
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
String data = (row.getCell(j).getStringCellValue()+ "");
excelData[j][i] = data;
}
}
This transpose data when storing it into the array (note: excelData[j][i] and not excelData[i][j]).
With this, you can get all the contents of the first column as excelData[0].
No matter what code snippet that I try, of which I find on the Internet (mostly from Stack Exchange/Overflow), I can't figure out how to convert (or "assign") elements of a one-dimensional array into a two-dimensional array.
String str = in.next(); // Read the incoming text file and store it as a string
char[] oneDcharArray = str.toCharArray(); // Convert the string into a 1D array
maze = new char[numberOfRows][numberOfColumns]; // Assign row/column size to 2D array
int count = 0;
for (row = 0; row < numberOfRows; row++)
{
for (column = 0; column < numberOfColumns; column++)
{
// Convert 1D array into 2D array
maze[row][column] = oneDcharArray[count]; // Error: ArrayIndexOutOfBoundsException
count++;
}
}
The answer by Jags below works well, but it's not perfect. It prints:
Row 0: ++++++++++
Row 1: S+++++++++
Row 2: ++++++++++
Row 3: +++++ 0000 0000 0000 0000 0000
Row 0: ++++++++++
Row 1: OOOOOOOOOO
......
//rows*col must equal to single d array
public static char[][] conversion( char[] array, int rows, int cols )
{
if (array.length != (rows*cols))
throw new IllegalArgumentException("Invalid array length");
char[][] array2d = new char[rows][cols];
for ( int i = 0; i < rows; i++ )
System.arraycopy(array, (i*cols), array2d[i], 0, cols);
return array2d;
}
Below sample code should work. You need to loop through oneDcharArray rather then rows/columns. But note that, it all depends on what is your requirement to create maze. i.e how exactly you want to devide available chars into N x M array.
public class OneToTwo {
public static void main(String[] args) {
String str = "This is my test string with some words in it.";
char[] oneDcharArray = str.toCharArray(); // Convert the string into a 1D array
int numberOfColumns = 10;
int numberOfRows = (int)Math.ceil(oneDcharArray.length/numberOfColumns) + 1; // its not modulo
char[][] maze = new char[numberOfRows][numberOfColumns]; // Assign row/column size to 2D array
int count = 0;
int row =0 ,column = 0;
for (char c:oneDcharArray) {
if(column >= numberOfColumns) {
row++;
column = 0;
}
maze[row][column] = c;
column++;
}
//Test it
for (row = 0; row < numberOfRows; row++) {
System.out.print("Row "+row+": ");
for (column = 0; column < numberOfColumns; column++) {
// Convert 1D array into 2D array
System.out.print(maze[row][column]);
count++;
}
System.out.println();
}
}
}
output
Row 0: This is my
Row 1: test stri
Row 2: ng with so
Row 3: me words i
Row 4: n it.