Reputation: 27
I'm trying to delete an element from an array by accepting the array as well as the element to be deleted. But when I print the array, the element prev to the element to be deleted is being displayed. How can I correct this?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class delete {
void main() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of numbers");
int n = Integer.parseInt(br.readLine());
int x[] = new int[n];
System.out.println("Enter the numbers");
for (int i = 0; i < n; i++) {
x[i] = Integer.parseInt(br.readLine());
}
System.out.println("Enter the number you want to delete");
int d = Integer.parseInt(br.readLine());
boolean b;
int i = 0;
for (; i < n; i++) {
if (x[i] == d) {
b = true;
break;
}
}
int q = i;//index position of the element to be deleted
int x2[] = new int[n - 1];
for (int k = 0; k < n - 1; k++) {
if (q != k)
x2[k] = x[k];
if (q == k)
x2[k] = x[k + 1];
}
for (int j = 0; j < n - 1; j++) {
System.out.println(x2[j]);
}
}
}
Upvotes: 1
Views: 83
Reputation: 17567
The problematic snippet in OPs code is:
for (int k = 0; k < n - 1; k++) {
if (q != k)
x2[k] = x[k];
if (q == k)
x2[k] = x[k + 1];
}
As said in my first comment, this is not able to correctly write each value behind q
into the new array.
Let's assume the following variables:
int n = 9;
int q = 5;
int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] x2 = new int[n - 1];
After running the mentioned loop, x2
will then be [1, 2, 3, 4, 5, 7, 7, 8]
, because in if (q == k)
OP writes the value of the following index, if it reaches the ignored index and on the next iteration it writes the excact same index again with if (q != k) x2[k] = x[k];
. That is why "7" occurs twice.
An easy way to fix this is using two separates loops, like OP has done after my suggestion:
for (int k = 0; k < q; k++) {
x2[k] = x[k];
}
for (int k = q; k < n - 1; k++) {
x2[k] = x[k+1];
}
The first loop writes each value before the ignored index and the second loop writes each value behind the ignored index.
Upvotes: 1