我一直在尝试创建一个程序,它将从用户想要的数组中删除一个元素,并在循环中删除该数组。我遇到的问题是在删除元素后删除额外的数组元素。我已经在这里待了大约3个小时而且没有在哪里。请帮我。谢谢。
这就是我的意思:
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
这就是我所拥有的:
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);
}
}
答案 0 :(得分:2)
问题出在打印结果的代码中:它总是假设只有一个项目被“删除”。当然你无法真正从数组中删除项目 - 你所能做的就是假装最后的K
元素不存在,而不是打印它们。
你需要让计数知道何时停止 - 换句话说,而不是
for (int a = i; a < intArray.length - 1; a++ )
你应该写
for (int a = i; a < intArray.length - removedCount; a++ )
从零开始removedCount
,并在每次删除元素时递增它。