英文:
I cannot use java array.remove() on int[]
问题
以下是翻译好的内容:
我刚接触Java,并且我在一门课程中需要为作业从数组中移除重复元素,但是我在我的代码中遇到了一个障碍:
异常线程"main" java.lang.Error: 未解决的编译问题:
无法在数组类型int[]上调用remove(int)
at File10.main(File10.java:17)
这是我目前的代码:
```java
import java.util.ArrayList;
public class Homework10 {
public static void main(String[] args) {
int arrayLength = (int) (Math.random()*50);
int[] randomArray = new int[arrayLength];
for (int i =0; i<arrayLength; i++) {
randomArray[i] = (int) (Math.random()*20);
}
System.out.println("原始数组:");
for (int i =0; i<arrayLength; i++) {
System.out.print(randomArray[i] + " ");
}
for (int i =0; i<randomArray.length; i++) {
for (int k =(i + 1); k<randomArray.length; k++) {
if (randomArray[i] == randomArray[k]) {
randomArray.remove(k);
}
}
}
}
}
我已经检查过的所有内容要么与我的代码无关,要么证明我的代码中不应该有错误。
<details>
<summary>英文:</summary>
I am new to Java, and I am in a class where for the homework, I need to remove duplicate elements in an array, but I have come across an obstacle in my code:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot invoke remove(int) on the array type int[]
at File10.main(File10.java:17)
This is my code so far:
```java
import java.util.ArrayList;
public class Homework10 {
public static void main(String[] args) {
int arrayLength = (int) (Math.random()*50);
int[] randomArray = new int[arrayLength];
for (int i =0; i<arrayLength; i++) {
randomArray[i] = (int) (Math.random()*20);
}
System.out.println("Original Array:");
for (int i =0; i<arrayLength; i++) {
System.out.print(randomArray[i] + " ");
}
for (int i =0; i<randomArray.length; i++) {
for (int k =(i + 1); k<randomArray.length; k++) {
if (randomArray[i] == randomArray[k]) {
randomArray.remove(k);
}
}
}
}
}
Everything I have checked either does not relate to my code or proves that there shouldn't be an error in my code.
答案1
得分: 1
在数组上没有 remove()
方法。请使用 ArrayList,或阅读关于数组的API文档。
英文:
There is no remove()
method on an array. Use an ArrayList, or read the api on arrays.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论