我无法在 int[] 数组上使用 java array.remove()。

huangapple go评论92阅读模式
英文:

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&lt;arrayLength; i++) {
			randomArray[i] = (int) (Math.random()*20);
		}
		System.out.println(&quot;Original Array:&quot;);
		for (int i =0; i&lt;arrayLength; i++) {
			System.out.print(randomArray[i] + &quot; &quot;);
		}
		for (int i =0; i&lt;randomArray.length; i++) {
			for (int k =(i + 1); k&lt;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.

huangapple
  • 本文由 发表于 2020年8月23日 09:15:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63542533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定