Removing a row matching a condition from a 2D array using for loop
i´m having an issue. I´m trying to remove a row from a 2D array which match a certain condition. I previously created a 2D array using
String [][] T = new String [line][column];
The user can choose the number of lines and column and populate the table with the value of his choice. One of the column must contain prices of items and those prices will be compared to a price limit given by the user and every item below the price must be deleted from the 2D array (the row). I have been told to use array. But here I need to use "for loop" and a 2D table.
So far that s what i have for the "removing part"
public static String[][] deleterow(String[][]T, int priceLimit)
{
// count number of lines matching the condition (used later to redefine the new size)
int count=0;
int priceItem;
for (int i=0; i<T.length;i++)
{
for (int j=3; j<T[i].length;j++) // 4th colomn should contains prices
{
priceItem = Integer.parseInt(T[i][j]);
if (priceItem< priceLimit)
{
count=count+1;
}
}
}
String [][]T3 = new String [T.length-count][];
for (int i=0; i<T.length;i++)
{
for (int j=0; j<T[i].length;j++)
{
priceItem = Integer.parseInt(T[i][j]);
if(priceItem < priceLimit)
{
T3[i][j]=T[i+1][j];
}
else
{
T3[i][j]=T[i][j];
}
}
}
System.out.println(count+" items deleted from the table");
Unfortunately i´m having a problem with the parsing from String to Int here so the code is not going further. What can be improved?
Solution 1:
Here's a simple method that turns rows into null values if the 4th column is smaller than priceLimit, you'll have an array with null values after calling the method, but you can look up here Remove Null Value from String array in java to figure out how to remove null values from the array.
public static void main(String[] args) {
int lines = 4;
int columns = 4;
String[][] twoDArray = new String [lines][columns];
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
twoDArray[i][j] = "test";
}
}
twoDArray[0][3] = "5";
twoDArray[1][3] = "10";
twoDArray[2][3] = "15";
twoDArray[3][3] = "20";
System.out.println(Arrays.toString(twoDArray));
deleteMatchingRow(twoDArray, 16);
System.out.println(Arrays.toString(twoDArray));
}
public static void deleteMatchingRow (String[][] twoDArray, int priceLimit) {
for (int i = 0; i < twoDArray.length; i++) {
if (Integer.parseInt(twoDArray[i][3]) < priceLimit) {
twoDArray[i] = null;
}
}
}
Now regarding your exception java.lang.NumberFormatException
you just have to make sure that in every row, the 4th column is indeed a parsable Integer and not a random String.
Notice how in the main method I filled all the two D array with "test"
and then reassigned the 4th column of every row into String numbers so they can be parsed by Integer.parseInt()