Reputation: 1
I want to remove an element after creating the below 2d array.And it should be the last element of the array.
public static void main(String[] args) {
int i;
int row = 2;
int col = 2;
String[][] queue = new String[row][col];
Scanner scanner = new Scanner(System.in);
String[][] queue = new String[row][col];
Scanner scanner = new Scanner(System.in);
for (row = 0; row < queue.length; row++) { // Loop through the rows in the 2D array.
for (col = 0; col < queue[row].length; col++) {
System.out.println("Enter the name");{
queue[row][col] = scanner.next();
}
}
}
for (i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(queue[i][j] + " ");
Upvotes: 0
Views: 1483
Reputation: 40034
You cannot remove a cell from an array. But you can effectively
remove it by simply replacing the last row with a new copy of all but the last element.
queue[row-1] = Arrays.copyOf(queue[row-1], queue[row-1].length-1);
You might want to try creating the array like this. Then you won't need to remove or copy anything.
int[] array
of dimensions for each row.int rows = 2;
String[][] queue = new String[rows][];
queue[0] = new String[2];
queue[1] = new String[1];
Scanner scanner = new Scanner(System.in);
for (rows = 0; rows < queue.length; rows++) { // Loop through the rows in the 2D array.
for (int col = 0; col < queue[rows].length; col++) {
System.out.println("Enter the name");{
queue[rows][col] = scanner.next();
}
}
}
for (String[] row : queue) {
System.out.println(Arrays.toString(row));
}
Upvotes: 0
Reputation: 391
The question is awkward.
queue[row - 1][col - 1] = ""
.Upvotes: 3