sách gpt4 ai đã đi

java - 制作一个从java中的数组中删除零的方法

In lại 作者:行者123 更新时间:2023-12-01 18:06:37 26 4
mua khóa gpt4 Nike

很好奇如何编写一个方法来从数组中删除所有零。如果我在 main 方法中有数组。例如我的主要方法看起来像

  public static void main(String[] args) {
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
System.out.println(Arrays.toString(test) + ": length = " + test.length);
int[] result = removeZeros(test);
System.out.println(Arrays.toString(result) + ": length = " + result.length);
}

并让代码输出长度和不带零的数组,例如:

 [1, 0, 4, 7, 0, 2, 10, 82, 0]: length = 9
[1, 4, 7, 2, 10, 82]: length = 6

除了这样做之外,我不知道如何为此编写方法:

  int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
int length = 0;
for (int i=0; i
if (test[i] != 0)
length++;
}
int [] intResult = new int[length];
for (int i=0, j=0; i
if (test[i] != 0) {
intResult[j] = test[i];
j++;
}
}

有什么想法如何使它成为一个方法并让它打印出原始数组和新数组(其中不含零+长度)吗?

1 Câu trả lời

我没有测试它,但这应该有效:

public class Blah {

public static void main(String[] args) {
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
System.out.println(Arrays.toString(test) + ": length = " + test.length);
int[] result = removeZeros(test);
System.out.println(Arrays.toString(result) + ": length = " + result.length);
}

public int[] removeZeros(int[] test) {
int length = 0;
for (int i=0; i
if (test[i] != 0)
length++;
}
int [] intResult = new int[length];
for (int i=0, j=0; i
if (test[i] != 0) {
intResult[j] = test[i];
j++;
}
return intResult;
}

}

关于java - 制作一个从java中的数组中删除零的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953147/

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com