Reputation: 5
I have been trying to create a program that will remove a element from the array that the user wants, and to have the array deleting in a loop. The problem that I have is deleting the extra array elements after removing an element. I have been going at this for about 3 hours and got no where. Please help me. Thank you.
Here is what I mean:
The array list: 10 20 30 40 50
Which number should be removed for the list?
Number to delete: 20
10 30 40 50
Try again? y/n
Which number should be removed for the list?
Number to delete: 30
10 40 **50 50**
Try again? y/n
Here is what I have:
import java.util.Scanner;
public class DeleteElements {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int del = 0;
int intArray[] = {10, 20, 30, 40, 50};
System.out.println("\n---- Part 3 of the Homework----");
char yN;
boolean yes = true;
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
do {
System.out.print("\nWhich number should be removed for the list? ");
del = input.nextInt();
System.out.println("Number to delete: " + del);
for (int i = 0; i < intArray.length; i++) {
if (intArray[i] == del) {
if (i == 0) {
for (int b = i; b < intArray.length - 1; b++) {
intArray[b] = intArray[b + 1];
System.out.print(intArray[b] + " ");
}
}
if (i > 0 && i <= intArray[i]) {
for (int c = 0; c < i; c++) {
System.out.print(intArray[c] + " ");
}
for (int a = i; a < intArray.length - 1; a++) {
intArray[a] = intArray[a + 1];
System.out.print(intArray[a] + " ");
}
}
}
}
System.out.println("\nDelete again? y/n");
input.nextLine();
yN = input.nextLine().charAt(0);
if (yN == 'y') {
yes = true;
} else if (yN == 'n') {
yes = false;
}
} while (yes != false);
}
}
Upvotes: 0
Views: 66
Reputation: 726629
The problem is in the code that prints the result: it always assumes that only one item has been "removed". Of course you cannot really remove items from an array - all you can do is pretending that the last K
elements are not there, and not print them.
You need to keep the count to know when to stop - in other words, instead of
for (int a = i; a < intArray.length - 1; a++ )
you should write
for (int a = i; a < intArray.length - removedCount; a++ )
Start removedCount
at zero, and increment it each time you remove an element.
Upvotes: 2