gpt4 book ai didi

Java数组删除困惑?

转载 作者:行者123 更新时间:2023-12-02 05:53:16 24 4
gpt4 key购买 nike

我一直在尝试创建一个程序,该程序将从用户想要的数组中删除一个元素,并让数组在循环中删除。我遇到的问题是删除元素后删除多余的数组元素。我已经这样做了大约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);
}
}

最佳答案

问题出在打印结果的代码中:它总是假设只有一项被“删除”。当然,您无法真正从数组中删除项目 - 您所能做的就是假装最后一个 K 元素不存在,并且不打印它们。

您需要不断计数才能知道何时停止 - 换句话说,而不是

for (int a = i; a < intArray.length - 1; a++ )

你应该写

for (int a = i; a < intArray.length - removedCount; a++ )

从零开始removedCount,并在每次删除元素时递增它。

关于Java数组删除困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com